我正在使用HTML5和JavaScript制作游戏。
如何通过JavaScript播放游戏音频?
我正在使用HTML5和JavaScript制作游戏。
如何通过JavaScript播放游戏音频?
当前回答
这很简单,只需要获取音频元素并调用play()方法:
document.getElementById('yourAudioTag').play();
看看这个例子:http://www.storiesinflight.com/html5/audio.html
这个站点还提供了一些其他很酷的功能,比如load()、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>
var song = new Audio();
song.src = 'file.mp3';
song.play();
在react中,你可以使用ref:
// typescript
const audRef = useRef(null);
const playAudio = () => {
(audRef.current as any).play();
}
...
// html
<audio controls src={your_audio} ref={audRef} />
<button onClick={playAudio}>Play</button>
非常简单的解决方案,如果你有一个像下面这样的HTML标签:
<audio id="myAudio" src="some_audio.mp3"></audio>
只需使用JavaScript来播放它,就像这样:
document.getElementById('myAudio').play();
如果你想在当前浏览器选项卡未被选中的情况下也能播放声音,你必须在页面加载时加载音频资源。
像这样:
var audio = new Audio('audio/path.mp3');
function playSound(){
audio.play();
}
请参阅这个问题了解更多细节