我正在使用HTML5和JavaScript制作游戏。
我该如何通过JavaScript播放游戏音频?
var song = new Audio();
song.src = 'file.mp3';
song.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>
我使用这种方法来播放声音...
var audioElement;
if(!audioElement) {
audioElement = document.createElement('audio');
audioElement.innerHTML = '<source src="' + '/audio/sound.mp3'+ '" type="audio/mpeg" />'
}
audioElement.play();
const playAudio = (path = 'defaultPath') => new Audio(path).play()
playAudio('path')
var audio = new Audio('audio/path.mp3');
function playSound(){
audio.play();
}
请查看此问题以获取更多详细信息。
import $buzz from 'musquito';
const buzz = $buzz('gunfire.mp3');
buzz.play();
<script>
function playMusic(){
music.play();
}
</script>
<html>
<audio id="music" loop src="sounds/music.wav" autoplay> </audio>
</html>
and call this playMusic() whenever you need in your game code.
Just use this:
<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>
Sample:
<video controls="" autoplay="" name="media">
<source src="https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3" type="audio/mpeg">
</video>
我不知道这是否适用于Chrome 73之外的其他浏览器!!
// 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>
这是我在一项与婴儿人工智能相关的项目中想出来的一些 JavaScript 代码。希望这能对你有所帮助。
<!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>
<audio>
元素。该元素将具有适当的JS钩子,用于'play','pause'等操作... - Marc B