使用 createjs 系列的 preload.js 调用函数后音频未播放

The audio did not play after function called with preload.js of createjs' series

我开发了一款 HTML5 游戏。我使用 createjs 预加载图像。图片预加载完成后,需要自动播放BGM

我知道 chrome 新的音频政策。而且我很困惑我使用 function handleComplete 来触发音频。为什么它仍然不起作用?我应该如何让它发挥作用?

这是我的代码:


function Sound (id_str){ this.id = id_str; }

Sound.prototype.play = function () {

    //there are other logics, but can simply like below

    let audio = document.getElementById(this.id);
    audio.play().catch(e =>console.log(e));
};

var audio_bg = new Sound('bgm_id');


windows.onload = function preload (handleFileProgress,handleComplete){
    let manifest = [...];

    loader = new createjs.LoadQueue(false);
    loader.setMaxConnections(100);
    loader.maintainScriptOrder=true;
    loader.installPlugin(createjs.Sound);
    loader.loadManifest(manifest);
    loader.addEventListener('progress', handleFileProgress); 
    loader.addEventListener('complete', handleComplete);

};

function handleFileProgress(){...}

function handleComplete(){
    //...
    audio_bg.play();

}

我发现的错误是:

NotAllowedError: play() failed because the user didn't interact with the document first.

您看到的错误是由于浏览器中的安全性发生了变化,您无法在没有用户操作的情况下播放音频。 SoundJS 已经侦听浏览器输入事件 (mouse/keyboard/touch) 以解锁音频,但如果您在此之前尝试播放音频,则它将失败。

要显示此内容,请在加载文件之前快速单击浏览器,它可能会播放。

建议将音频置于用户事件之后,例如 "click to get started" 或类似的东西。这是浏览器安全改进的不幸副作用:)