How do I fail gracefully with a corrupted external wav file?

257 views Asked by At

I've got this code within an IEnumerator, and it's working perfectly well if I use a properly formatted wav file. But the files I'm loading are user-submitted, so I want to handle improperly formatted wav files. I made a 0-length text file and renamed it to appear like a wav file, and once the code reaches the "DownloadHandlerAudioClip.GetContent" call the app crashes with the following error:

Error: Cannot create FMOD::Sound instance for clip "" (FMOD error: Unsupported file or audio format. ) UnityEngine.Networking.DownloadHandlerAudioClip:GetContent (UnityEngine.Networking.UnityWebRequest) XMLFrobnicator/d__12:MoveNext () (at Assets/Scripts/XMLFrobnicator.cs:197) UnityEngine.SetupCoroutine:InvokeMoveNext (System.Collections.IEnumerator,intptr)

So it's not an Exception, otherwise the try/catch would catch it. Is there another way to catch this sort of thing? My friend suggested spawning another process, but I don't know if that's even possible with Unity. If I can't catch it, can I somehow test to see if the content of the UnityWebRequest is a valid wav file?

Here's my code:

    using (UnityWebRequest uwr = UnityWebRequestMultimedia.GetAudioClip(fileName, AudioType.WAV)) {
        yield return uwr.SendWebRequest();
        if(uwr.result != UnityWebRequest.Result.Success) {
            Debug.Log(uwr.error);
            yield break;
        }
        else {
            try {
                app.levelMusic = DownloadHandlerAudioClip.GetContent(uwr);
            }
            catch(System.Exception e) {
                Debug.Log(e);
                yield break;
            }
        }
    }
1

There are 1 answers

3
thunderkill On

If it's just to handle your response you won't have any problem ignoring it , the try and catch will work fine. Try this out and tell us the result this time

StartCoroutine(GetAudioClip());
IEnumerator GetAudioClip()
    {
    try { 
       using (UnityWebRequest uwr = UnityWebRequestMultimedia.GetAudioClip(fileName, AudioType.WAV)) {
            yield return uwr.SendWebRequest();
           if (uwr.result == UnityWebRequest.Result.ConnectionError)
            {
                Debug.Log(uwr.error);
            }
            else
            {
                AudioClip myClip = DownloadHandlerAudioClip.GetContent(uwr);
                app.levelMusic = myClip;
            }
        }
    }
       catch(Exception e) {
                    Debug.Log(e.message);
                    yield break;
                }
}