对象方法中的局部变量音频未播放 [英] Local variable audio in object method not playing

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

问题描述

我正在制作一款游戏,我希望在发生的事件中播放声音.我目前有一个如下所示的对象:

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.

我应该如何解决这个问题?

How should I fix this?

我只被允许使用 .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,它在播放成功开始时被解析.由于任何原因(例如权限问题)未能开始播放,都会导致承诺被拒绝.

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天全站免登陆