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

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


当前回答

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

其他回答

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

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

这是我在一个婴儿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>

我有一些问题与播放音频,特别是因为Chrome已经更新,用户必须首先与文档交互。

然而,在我发现的几乎所有解决方案中,JS代码都必须主动设置监听器(例如按钮点击)来接收用户事件,以便播放音频。

就我而言,我只是想让游戏在玩家与之互动时播放BGM,所以我为自己设置了一个简单的监听器,不断检查网页是否正在进行互动。

const stopAttempt = setInterval(() => {
    const audio = new Audio('your_audio_url_or_file_name.mp3');
    const playPromise = audio.play();
    if (playPromise) {
      playPromise.then(() => {
        clearInterval(stopAttempt)
      }).catch(e=>{
        console.log('' + e);
      })
    }
}, 100 )
var song = new Audio();
song.src = 'file.mp3';
song.play();

以下是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。