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

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


当前回答

new Audio('./file.mp3').play()

其他回答

在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>

这是我在一个婴儿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')`
var song = new Audio();
song.src = 'file.mp3';
song.play();

如果你想在当前浏览器选项卡未被选中的情况下也能播放声音,你必须在页面加载时加载音频资源。

像这样:

var audio = new Audio('audio/path.mp3');

function playSound(){
    audio.play();
}

请参阅这个问题了解更多细节