我正在使用HTML5和JavaScript制作游戏。
如何通过JavaScript播放游戏音频?
我正在使用HTML5和JavaScript制作游戏。
如何通过JavaScript播放游戏音频?
当前回答
以下是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。
其他回答
http://www.schillmania.com/projects/soundmanager2/
SoundManager 2提供了一个易于使用的API,允许声音在任何现代浏览器中播放,包括IE 6+。如果浏览器不支持HTML5,那么它可以从flash中获得帮助。如果你想严格使用HTML5而不使用flash,这里有一个设置,preferFlash=false
它在iPad、iPhone (iOS4)和其他支持html5的设备+浏览器上支持100%无flash音频
使用简单如下:
<script src="soundmanager2.js"></script>
<script>
// where to find flash SWFs, if needed...
soundManager.url = '/path/to/swf-files/';
soundManager.onready(function() {
soundManager.createSound({
id: 'mySound',
url: '/path/to/an.mp3'
});
// ...and play it
soundManager.play('mySound');
});
</script>
这里有一个实际的演示:http://www.schillmania.com/projects/soundmanager2/demo/christmas-lights/
我有一些关于音频承诺对象返回的问题和一些关于用户与声音交互的问题,我最终使用了这个小对象,
我建议执行最接近用户使用的交互事件的播放声音。
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>
就用这个吧:
<video controls="" autoplay="" name="media"><source src="Sound URL Here" type="audio/mpeg" /></video>
或者,简单点说:
<video controls="" autoplay="" name="media">
<source src="Sound URL Here" type="audio/mpeg" />
</video>
示例: <视频控制="" autoplay="" name="media"> <source src="https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3" type="audio/mpeg"> . < /视频>
不知道这是否适用于除Chrome 73之外的其他浏览器!!
在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>
你可以使用Web Audio API来播放声音。有相当多的音频库,如嚎叫.js, soundjs等。如果你不担心旧的浏览器,那么你也可以查看http://musquitojs.com/。它提供了一个简单的API来创建和播放声音。
例如,要播放一个声音,你所要做的就是。
import $buzz from 'musquito';
const buzz = $buzz('gunfire.mp3');
buzz.play();
该库还支持音频精灵。