我正在使用HTML5和JavaScript制作游戏。

如何通过JavaScript播放游戏音频?


当前回答

我用这个方法播放了一个声音…

var audioElement;
if(!audioElement) {
  audioElement = document.createElement('audio');
  audioElement.innerHTML = '<source src="' + '/audio/sound.mp3'+ '" type="audio/mpeg" />'
}
audioElement.play();

其他回答

就用这个吧:

<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之外的其他浏览器!!

这很简单,只需要获取音频元素并调用play()方法:

document.getElementById('yourAudioTag').play();

看看这个例子:http://www.storiesinflight.com/html5/audio.html

这个站点还提供了一些其他很酷的功能,比如load()、pause()和音频元素的其他一些属性。

这是我在一个婴儿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>
const playAudio = (path) => {
   new Audio(path ?? 'defaultPath').play()
}
    
playAudio('path')`

如果你想在页面打开时播放音频,那么就像这样做。

<脚本> 函数playMusic () { music.play (); } > < /脚本 < html > <audio id="music"循环src="sounds/music.wav" autoplay> </audio> .wav . < / html > 并在游戏代码中调用这个playMusic()。