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.

" + 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

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

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