简体   繁体   中英

How do I catch an audio DOMException caused by a file that cannot play?

If I try and play a non-existing audio file (eg the file hasn't downloaded yet) like this:

audio_object = new Audio("Non_Existing_Audio_File.mp3");
audio_object.play();

I get:

 Uncaught (in promise) DOMException: The media resource indicated by the src attribute or assigned media provider object was not suitable. 

That's fine, but how can I catch that error? If I do a try/catch, this is what happens:

function playAudioWithTryCatch()   {

            try {               
                audio_object.play();
                 //Result: Uncaught (in promise) DOMException: The media resource indicated by the src attribute or assigned media provider object was not suitable.          
            
            } catch (error) {
                // We never get here:
                console.error("Audio play failed",error);            
            }
            
        }

So with try/catch I never get as far as the catch block, only the same unhandled error message when the play method is called.

If I try using a Promise I get:

function playAudioWithPromise(){
   
            let myPromise = new Promise(function(resolve, reject) { 

                if (E2.play()) {
                    resolve("OK");
                } else {
                    reject("Error");
                }
            });

            myPromise.then(
                result => console.log(result), 
                error => console.log(error) 
            );
        

            //Result: Uncaught (in promise) DOMException: The media resource indicated by the src attribute or assigned media provider object was not suitable. 
            //And "OK" (console log)

        }

Again, the error is not caught, similar to above.

Can anyone tell me how to catch/handle this error before it gets output to the console?

I know I can use the media readyState property but that doesn't help in this case since I'm trying to work around a Safari issue whereby the readyState doesn't show ready until a user has initiated each and every audio file play method, which is impractical so I can't use that here.

Any help appreciated!

audio_object.play() itself returns a promise. Catch the error with a .catch() like a normal promise. I found that out by testing the following code and inspecting the variables in my browser:

function start() {
    audio_object = new Audio("Non_Existing_Audio_File.mp3");
    window.playResult = audio_object.play();
    playResult.catch(e => {
        window.playResultError = e;
    })
}

start();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM