Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by ThomasVandenberghe · Jul 15, 2014 at 09:09 AM · audiocachemp3

Saving mp3 files to caches and playing them

Hi, currently I've written a basic caching script, but now I'd need to be able to store audio files.

This is the code where I'm checking the cache and/or download the file.

 private IEnumerator CoroutineLoadFromCacheOrDownload(string url, int version, CachingType cachingType, Action<float> progress, Action<WWW, string> callBack)
         {
             bool wwwReturned = false;
             string cachePath = Application.temporaryCachePath + "/" + GetHashString(url + version);
 
             // Only check cache if version is > 0
             if (version > 0) {
                 // Check cache first if there is a file present
                 using (WWW www = new WWW("file://" + cachePath)) {
                     while (!www.isDone) {
                         if (progress != null)
                             progress(www.progress);
                         yield return 0;
                     }
                     yield return www;
                     if (www.error != null) {
                         Debug.Log("Didn't find a file in the cache. Proceeding to download from url.\n" + www.error);
                         // Didn't find a file in the cache.
                         // Code will proceed to download it from the url.
                     }
                     else {
                         // A file was found in the cache. Return this file, and skip the download.
                         if (progress != null)
                             progress(1);
                         if (callBack != null)
                             callBack(www, cachePath);
                         wwwReturned = true;
                     }
                 }
             }
 
             if (!wwwReturned) {
                 using (WWW www = new WWW(url)) {
                     while (!www.isDone) {
                         if (progress != null)
                             progress(www.progress);
                         yield return 0;
                     }
                     yield return www;
                     if (www.error != null) {
                         Debug.Log("Error downloading file :: " + www.error);
                         if (callBack != null)
                             callBack(null, "");
                     }
                     else {
                         // Only cache if version is 0 or higher
                         if (version >= 0) {
                             switch(cachingType) {
                             case CachingType.TEXTURE: // Save Texture2D to file
                                 {
                                     FileStream file = File.Open(cachePath, FileMode.Create);
 #if UNITY_IPHONE
                                     iPhone.SetNoBackupFlag(cachePath);
 #endif
                                     BinaryWriter binaryWriter = new BinaryWriter(file);
                                     binaryWriter.Write(www.bytes);
                                     file.Close();
                                 }
                                 break;
                             case CachingType.TEXTASSET: // Save text to file
                                 {
                                     FileStream file = File.Open(cachePath, FileMode.Create);
 #if UNITY_IPHONE
                                     iPhone.SetNoBackupFlag(cachePath);
 #endif
                                     StreamWriter streamWriter = new StreamWriter(file);
                                     streamWriter.Write(www.text);
                                     streamWriter.Close();
                                     file.Close();
                                 }
                                 break;
                             case CachingType.VIDEO: // Save video to file
                                 {
                                     FileStream file = File.Open(cachePath, FileMode.Create);
 #if UNITY_IPHONE
                                     iPhone.SetNoBackupFlag(cachePath);
 #endif
                                     BinaryWriter binaryWriter = new BinaryWriter(file);
                                     binaryWriter.Write(www.bytes);
                                     file.Close();
                                 }
                                 break;
                             case CachingType.AUDIO:
                                 {
                                     FileStream file = File.Open(cachePath, FileMode.Create);
 #if UNITY_IPHONE
                                     iPhone.SetNoBackupFlag(cachePath);
 #endif
                                     BinaryWriter binaryWriter = new BinaryWriter(file);
                                     binaryWriter.Write(www.bytes);
                                     file.Close();
                                 }
                                 break;
                             default:
                                 throw new Exception("Trying to save unknown file type.");
                             }
                         }
                         if (progress != null)
                             progress(1);
                         if (callBack != null)
                             callBack(www, cachePath);
                     }
                 }
             }
         }

When I'm accessing the file for the first time, it succesfully downloads and saves the data. The first time it's downloaded from the server, the second time from the cache. When downloaded from the cache however, no audio plays. Length and samples are both 0.

 if (www != null)
             {
                 Debug.Log("Byte size :: " + value.bytes.Length);
 
 //                audioClip = value.GetAudioClip(false, false, AudioType.MPEG);
                 audioClip = value.audioClip;
 
                 Debug.Log(audioClip.isReadyToPlay);
 
                 Debug.Log("url :: " + value.url);
                 Debug.Log("audioClip :: " + audioClip + " :: " + audioClip.length + " :: " + audioClip.samples);
               
                 audioReady = true;
 
                 TryAndPlayVideo();
             }

When I export the saved data via iExplorer, I can open and play the file as it should be. This method works on mac and android, but seems to fail on iOS.

Any idea how I would be able to save mp3 files and play them from the device again?

Kind regards, Thomas

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
1

Answer by Eng.Ahmed.Fawzy · May 27, 2015 at 01:51 PM

Hi There, Actually i want to thank you alot for this code, your code could solve alot of problem to me, so i want to give back thing, your code problem is just the extension like ".mp4",".mp3",".jpg" first time your code can recognize the file type and parse it, next time load from cache there is no extension so it doesn't load well as it should be.

what you can do is modify the cachepath to include file extention path+".extension" according to cahceType it run well over android/iOS

Best Regards, Ahmed

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by Rouge Digital · Jul 03, 2016 at 09:44 PM

I maid an Asset play mp3 files, it works on Win, Max, Linux, iOS, android... It works for local files and web streams.

This will play your songs and decode them into a unity audiosource.

Asset - uAudio: Mp3 Player/Streamer

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

24 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Load MP3 file in code 0 Answers

MP3 to OGG Converter, Plugin, Command Line to be used with Unity 1 Answer

Existing solution for load MP3 from disc ? 2 Answers

Why Won't My Audioclip Loop Seamlessly? 1 Answer

Large music files make asset importing slow / game large. Compression ideas? 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges