簡體   English   中英

如何捕獲由無法播放的文件引起的音頻 DOMException?

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

如果我嘗試播放一個不存在的音頻文件(例如,該文件尚未下載),如下所示:

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

我得到:

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

很好,但是我怎樣才能捕捉到這個錯誤呢? 如果我執行 try/catch,就會發生以下情況:

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);            
            }
            
        }

因此,對於 try/catch,我永遠不會到達 catch 塊,只有在調用 play 方法時出現相同的未處理錯誤消息。

如果我嘗試使用 Promise,我會得到:

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)

        }

同樣,錯誤沒有被捕獲,與上面類似。

誰能告訴我如何在將 output 發送到控制台之前捕獲/處理此錯誤?

我知道我可以使用媒體readyState屬性,但這在這種情況下沒有幫助,因為我正在嘗試解決 Safari 問題,即 readyState 在用戶啟動每個音頻文件播放方法之前不會顯示就緒,這是不切實際的,所以我不能在這里使用它。

任何幫助表示贊賞!

audio_object.play()本身返回 promise。使用.catch()捕獲錯誤,就像正常的 promise 一樣。我通過測試以下代碼並檢查瀏覽器中的變量發現了這一點:

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

start();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM