audio.1.html:39 Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.


一、audio.1.html:39 Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.

Audio 標簽的 autoplay 自動播放功能受限制。

針對於新版谷歌瀏覽器、火狐瀏覽器。

對於IE,Edge瀏覽器還是支持自動播放的。

規則要求:

在用戶發生交互的情況下,開啟播放。禁止頁面加載完,自動播放。

Chrome報錯提示最為友善,意思是說,用戶還沒有交互,不能調play。用戶的交互包括哪些呢?包括用戶觸發的touchend, click, doubleclick或者是 keydown事件,在這些事件里面就能調play.

二、Chrome的autoplay政策在2018年4月做了更改。

新的行為:瀏覽器為了提高用戶體驗,減少數據消耗,現在都在遵循autoplay政策,Chrome的autoplay 政策非常簡單

  1. muted autoplay始終被允許

  2. 音樂的autoplay 只有在下面集中情況下起作用:

    1. 有用戶行為發生像(click,tap,etc).

    2. 對於桌面程序,用戶已經提前播放了音頻

    3. 對於移動端用戶將音頻網址home screen.

開啟配置,解決方案:

1、 打開chrome
2、輸入 chrome://flags/#autoplay-policy
3、點擊default,選擇 Setting No user gesture is required
4、 重啟chrome

 

三、Audio Context 

The AudioContext was not allowed to start. It must be resumed (or created) after a user gesture on the page.

 

使用Audio Context 解決自動播放問題: 新版谷歌瀏覽器不支持自動播放,火狐 或者Edge瀏覽器支持

<script>
    //使用 AudioContext 實現
    var ctx = new AudioContext();
    //使用Ajax獲取音頻文件
    //var url = 'http://cdn.jnqianle.cn/audio/mouse.mp3';
    var url = 'http://cdn.jnqianle.cn/audio/notify1.mp3';
    var request = new XMLHttpRequest();
    request.open('GET', url, true);
    request.responseType = 'arraybuffer';//配置數據的返回類型
    //加載完成
    request.onload = function () {
        var arraybuffer = request.response;
        console.info(arraybuffer);
        ctx.decodeAudioData(arraybuffer, function (buffer) {
            //處理成功返回的數據類型為AudioBuffer 
            console.info(buffer);
            //創建AudioBufferSourceNode對象
            source = ctx.createBufferSource();
            source.buffer = buffer;
            source.connect(ctx.destination);
            //指定位置開始播放
            source.start(0);
            console.info(source);
        }, function (e) {
            console.info('處理出錯');
        });
    }
    request.send();
</script>

 

更多:

HTML5 多媒體之<audio>標簽 使用 

新版本chrome瀏覽器(80版本以后)帶來的跨域請求cookie丟失問題  

HTML5 多媒體之<img>標簽 使用 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM