播放AUDIO时未捕获Google Chrome(承诺)DOMException [英] Google Chrome Uncaught (in promise) DOMException while playing AUDIO

查看:62
本文介绍了播放AUDIO时未捕获Google Chrome(承诺)DOMException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Chrome浏览器阻止自动播放音频/视频.我已经找到了自动播放视频的解决方案,但是我的用例需要自动播放音频.这是我的代码:

Chrome blocks auto-playing audio/video. I've found solutions for auto-playing video, but my use case requires auto-playing audio. Here is my code:

let audio = new Audio('music/test.mp3'); audio.play(); audio.loop = true;

这会导致未捕获(承诺)的DOMException".由于采用了新政策,因此在Chromium浏览器上使用.

This results in an "Uncaught (in promise) DOMException" on Chromium browsers because of new policies.

推荐答案

由于未处理错误,因此您收到未捕获的异常.

You're receiving an uncaught exception because you aren't handling an error.

https://developer.mozilla.org/zh-美国/docs/Web/API/HTMLMediaElement/播放

Audio是一个 HTMLMediaElement 对象,并且 play()方法返回一个promise.因此,我建议您处理该错误.

Audio is an HTMLMediaElement object, and the play() method returns a promise. Therefore I recommend handling the error.

var promise = audio.play();
if (promise) {
    //Older browsers may not return a promise, according to the MDN website
    promise.catch(function(error) { console.error(error); });
}

可能是以下两个错误之一:

One of two errors are possible:

NotSupportedError

这意味着浏览器不支持音频源(可能是由于音频格式)

This means that the audio source is not supported by the browser (probably due to audio format)

NotAllowedError

这是我怀疑您正在触发的那个.这意味着用户需要显式触发 audio.play(),因此该方法仅在响应用户生成的事件(如单击事件)时才可用.

This is the one I suspect you are triggering. This means the user needs to explicitly trigger the audio.play(), so the method is only usable if it is in response to a user generated event such as a click event.

文档:

用户代理(浏览器)或操作系统不允许在当前上下文或情况下播放媒体.例如,如果浏览器要求用户通过单击播放"按钮显式启动媒体播放,则可能会发生这种情况.

The user agent (browser) or operating system doesn't allow playback of media in the current context or situation. This may happen, for example, if the browser requires the user to explicitly start media playback by clicking a "play" button.

这篇关于播放AUDIO时未捕获Google Chrome(承诺)DOMException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆