我正在使用HTML5和JavaScript制作游戏。
如何通过JavaScript播放游戏音频?
我正在使用HTML5和JavaScript制作游戏。
如何通过JavaScript播放游戏音频?
当前回答
我用这个方法播放了一个声音…
var audioElement;
if(!audioElement) {
audioElement = document.createElement('audio');
audioElement.innerHTML = '<source src="' + '/audio/sound.mp3'+ '" type="audio/mpeg" />'
}
audioElement.play();
其他回答
这很简单,只需要获取音频元素并调用play()方法:
document.getElementById('yourAudioTag').play();
看看这个例子:http://www.storiesinflight.com/html5/audio.html
这个站点还提供了一些其他很酷的功能,比如load()、pause()和音频元素的其他一些属性。
添加一个隐藏的<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 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>
我有一些问题与播放音频,特别是因为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 song = new Audio();
song.src = 'file.mp3';
song.play();