对象方法中的本地变量音频无法播放 [英] Local variable audio in object method not playing

查看:217
本文介绍了对象方法中的本地变量音频无法播放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个游戏,我想在事件发生时播放声音.我目前有一个如下所示的对象:

I'm making a game, and I want sounds to play on events occurring. I have currently got an object that looks like below:

var soundObject = {
    invaderShoot: function() {
        var audio = new Audio("laser.wav");
        audio.play();
    },
    //Many more of the same method
};

然后我正在播放如下声音:

And then I'm playing the sounds like this:

soundObject.invaderShoot();

但是,当我尝试执行此操作时,它会出现以下错误:

However, when I try to do this, it comes up with the following error:

Unhandled Promise Rejection: NotAllowedError: The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.

然后在方法中突出显示此行:

And it comes up highlighting this line in the method:

audio.play();

出什么问题了?我已经搜索了GitHub线程和Stack Overflow问题,但是找不到错误的定义,更不用说如何解决了.

What is the problem? I have searched through GitHub threads and Stack Overflow questions, but I cannot find a definition of what the error is, let alone how to fix it.

我该如何解决?

只允许我使用.wav文件,因为那是我的代码托管服务允许的唯一文件格式.

I am only permitted to use .wav files, because that is the only file format that my code hosting service allows.

推荐答案

Audio.play()返回一个Promise,当成功开始播放后,该Promise将被解决.由于任何原因(例如权限问题)而无法开始播放,将导致诺言被拒绝.

Audio.play() returns a Promise which is resolved when playback has been successfully started. Failure to begin playback for any reason, such as permission issues, result in the promise being rejected.

const playedPromise = audio.play();
if (playedPromise) {
        playedPromise.catch((e) => {
            if (e.name === 'NotAllowedError' ||
                e.name === 'NotSupportedError') {
                //console.log(e.name);
            }
        });
    }

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

In your case, looks like your browser/os does not allow automatic playing of audio. 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. Here is the reference.

就自动播放而言,您可能需要根据新的浏览器策略在HTML中添加AudoContext. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#webaudio

As far as AutoPlay is concerned, you might need to add AudoContext in your HTML as per new browser policy. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#webaudio

编辑

window.onload = function() {
  var context = new AudioContext();
  // Setup all nodes
  ...
}
context.resume().then(() => {
    audio.play();
    console.log('Playback resumed successfully');
  });

这篇关于对象方法中的本地变量音频无法播放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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