我正在使用HTML5和JavaScript制作游戏。
如何通过JavaScript播放游戏音频?
我正在使用HTML5和JavaScript制作游戏。
如何通过JavaScript播放游戏音频?
当前回答
就用这个吧:
<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之外的其他浏览器!!
其他回答
就用这个吧:
<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之外的其他浏览器!!
这是我在一个婴儿AI项目上提出的一些JS。我希望这对你有所帮助。
<!DOCTYPE html>
<html>
<head>
<title>
js prompt AI
</title>
<style>
#button {
border: 1px solid black;
border-radius: 10px;
font-size: 22px;
height:65px;
width:100px;
text-align: center;
line-height: 65px;
}
</style>
</head>
<body>
<audio id="myAudio" src="./how_are_you.m4a"></audio>
<p>To Interact with the AI please click the button</p>
<div id=button>click</div>
<script>
var button = document.getElementById("button");
function playBack() {
button.addEventListener("click", function (){
var talk = prompt("If you wish for the AI to respond type hi");
var myAudio = document.getElementById("myAudio");
if(talk === "hi") {
myAudio.play();
}
}) ;
}
playBack();
</script>
</body>
</html>
我有一些关于音频承诺对象返回的问题和一些关于用户与声音交互的问题,我最终使用了这个小对象,
我建议执行最接近用户使用的交互事件的播放声音。
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秒后开始。
你可以使用Web Audio API来播放声音。有相当多的音频库,如嚎叫.js, soundjs等。如果你不担心旧的浏览器,那么你也可以查看http://musquitojs.com/。它提供了一个简单的API来创建和播放声音。
例如,要播放一个声音,你所要做的就是。
import $buzz from 'musquito';
const buzz = $buzz('gunfire.mp3');
buzz.play();
该库还支持音频精灵。