我正在使用HTML5和JavaScript制作游戏。
如何通过JavaScript播放游戏音频?
我正在使用HTML5和JavaScript制作游戏。
如何通过JavaScript播放游戏音频?
当前回答
这是一个相当老的问题,但我想补充一些有用的信息。话题发起者提到他正在“制作一款游戏”。所以对于所有需要音频进行游戏开发的人来说,有比<audio>标签或HTMLAudioElement更好的选择。我认为你应该考虑使用Web Audio API:
虽然网页上的音频不再需要插件,但音频标签为实现复杂的游戏和交互式应用程序带来了巨大的限制。Web Audio API是一个高级JavaScript API,用于在Web应用程序中处理和合成音频。此API的目标是包含现代游戏音频引擎中的功能,以及现代桌面音频制作应用程序中的一些混合、处理和过滤任务。
其他回答
根据安全要求,用户必须与网页进行交互才能允许音频,这就是我的做法,基于阅读许多文章,包括在这个网站上
在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();
重复需要,但不要暂停你想听到的音频时,游戏开始
我有一些关于音频承诺对象返回的问题和一些关于用户与声音交互的问题,我最终使用了这个小对象,
我建议执行最接近用户使用的交互事件的播放声音。
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>
如果你得到以下错误:
DOMException: play()失败,因为用户 没有首先与文档交互。
这意味着用户需要首先与网站进行交互(正如错误消息所说)。在这种情况下,您需要使用点击或只是另一个事件监听器,以便用户可以与您的网站进行交互。
如果你想自动加载音频,并且不希望用户首先与文档交互,你可以使用setTimeout。
setTimeout(() => { document.getElementById('mySound').play(); }, 500) <audio id=“mySound” src=“sound.mp3”></audio>
声音将在0.5秒后开始。
添加一个隐藏的<audio>元素,并按所示播放。
function playSound(url) {
var ourAudio = document.createElement('audio'); // Create a audio element using the DOM
ourAudio.style.display = "none"; // Hide the audio element
ourAudio.src = url; // Set resource to our URL
ourAudio.autoplay = true; // Automatically play sound
ourAudio.onended = function() {
this.remove(); // Remove when played.
};
document.body.appendChild(ourAudio);
}
var song = new Audio();
song.src = 'file.mp3';
song.play();