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

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


当前回答

如果你得到以下错误:

DOMException: play()失败,因为用户 没有首先与文档交互。

这意味着用户需要首先与网站进行交互(正如错误消息所说)。在这种情况下,您需要使用点击或只是另一个事件监听器,以便用户可以与您的网站进行交互。

如果你想自动加载音频,并且不希望用户首先与文档交互,你可以使用setTimeout。

setTimeout(() => { document.getElementById('mySound').play(); }, 500) <audio id=“mySound” src=“sound.mp3”></audio>

声音将在0.5秒后开始。

其他回答

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

添加一个隐藏的<audio>元素,并按所示播放。

function playSound(url) {
  var ourAudio = document.createElement('audio'); // Create a audio element using the DOM
  ourAudio.style.display = "none"; // Hide the audio element
  ourAudio.src = url; // Set resource to our URL
  ourAudio.autoplay = true; // Automatically play sound
  ourAudio.onended = function() {
    this.remove(); // Remove when played.
  };
  document.body.appendChild(ourAudio);
}

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

像这样:

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

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

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

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

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