我正在使用HTML5和JavaScript制作游戏。
如何通过JavaScript播放游戏音频?
我正在使用HTML5和JavaScript制作游戏。
如何通过JavaScript播放游戏音频?
当前回答
我有一些问题与播放音频,特别是因为Chrome已经更新,用户必须首先与文档交互。
然而,在我发现的几乎所有解决方案中,JS代码都必须主动设置监听器(例如按钮点击)来接收用户事件,以便播放音频。
就我而言,我只是想让游戏在玩家与之互动时播放BGM,所以我为自己设置了一个简单的监听器,不断检查网页是否正在进行互动。
const stopAttempt = setInterval(() => {
const audio = new Audio('your_audio_url_or_file_name.mp3');
const playPromise = audio.play();
if (playPromise) {
playPromise.then(() => {
clearInterval(stopAttempt)
}).catch(e=>{
console.log('' + e);
})
}
}, 100 )
其他回答
我有一些关于音频承诺对象返回的问题和一些关于用户与声音交互的问题,我最终使用了这个小对象,
我建议执行最接近用户使用的交互事件的播放声音。
var soundPlayer = {
audio: null,
muted: false,
playing: false,
_ppromis: null,
puse: function () {
this.audio.pause();
},
play: function (file) {
if (this.muted) {
return false;
}
if (!this.audio && this.playing === false) {
this.audio = new Audio(file);
this._ppromis = this.audio.play();
this.playing = true;
if (this._ppromis !== undefined) {
this._ppromis.then(function () {
soundPlayer.playing = false;
});
}
} else if (!this.playing) {
this.playing = true;
this.audio.src = file;
this._ppromis = soundPlayer.audio.play();
this._ppromis.then(function () {
soundPlayer.playing = false;
});
}
}
};
并执行如下:
<button onclick="soundPlayer.play('https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3');">Play</button>
var song = new Audio();
song.src = 'file.mp3';
song.play();
如果你想在页面打开时播放音频,那么就像这样做。
<脚本> 函数playMusic () { music.play (); } > < /脚本 < html > <audio id="music"循环src="sounds/music.wav" autoplay> </audio> .wav . < / html > 并在游戏代码中调用这个playMusic()。
根据安全要求,用户必须与网页进行交互才能允许音频,这就是我的做法,基于阅读许多文章,包括在这个网站上
在html中定义所需的音频文件 有一个带有点击的开始游戏按钮 当按钮被点击,然后播放和暂停所有的音频文件,除了一个你想在开始播放
因为所有的音频文件都是在同一个OnClick上“播放”的,你现在可以在游戏中的任何时间不受限制地播放它们
注意,为了最好的兼容性,不要使用wav文件,MS不支持它们
使用mp3和ogg,可以覆盖所有设备
例子:
<audio id="welcome">
<source src="URL/welcome.ogg" type="audio/ogg">
<source src="URL/welcome.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
根据需要重复游戏中的所有音频
然后:
document.getElementById("welcome").play();
document.getElementById("welcome").pause();
重复需要,但不要暂停你想听到的音频时,游戏开始
以下是2020年你看到错误时的解决方案:
[Error] Unhandled Promise Rejection: NotSupportedError:不支持该操作。 (匿名函数) rejectPromise 玩 (匿名函数)(testaudio.html:96) 调度(jquery-3.4.1.min.js 2:42577):
<div onclick="new Audio('/assets/test.mp3').play()">aaa</div>
不要太圆滑,觉得这是老式的oclick,我把它移到下面的jQuery或外部JavaScript文件中。没有。它需要是一个onclick。