我正在使用HTML5和JavaScript制作游戏。
如何通过JavaScript播放游戏音频?
我正在使用HTML5和JavaScript制作游戏。
如何通过JavaScript播放游戏音频?
当前回答
在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>
其他回答
在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>
以下是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。
如果你不想打乱HTML元素:
var audio = new Audio('audio_file.mp3');
audio.play();
功能播放(){ var audio = new audio ('https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3'); audio.play (); } <按钮onclick = "打()“>播放音频> < /按钮
这使用了HTMLAudioElement接口,它以与<audio>元素相同的方式播放音频。
如果你需要更多的功能,我使用了嚎叫.js库,发现它简单而有用。
< script src = " https://cdnjs.cloudflare.com/ajax/libs/howler/2.1.1/howler.min.js " > < /脚本> < >脚本 var声音=新的嚎叫({ src(“https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3”):, 体积:0.5, Onend:函数(){ 警报(“完成了!”); } }); sound.play () > < /脚本
我有一些关于音频承诺对象返回的问题和一些关于用户与声音交互的问题,我最终使用了这个小对象,
我建议执行最接近用户使用的交互事件的播放声音。
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>
这很简单,只需要获取音频元素并调用play()方法:
document.getElementById('yourAudioTag').play();
看看这个例子:http://www.storiesinflight.com/html5/audio.html
这个站点还提供了一些其他很酷的功能,比如load()、pause()和音频元素的其他一些属性。