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

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


当前回答

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

其他回答

如果你得到以下错误:

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

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

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

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

声音将在0.5秒后开始。

这很简单,只需要获取音频元素并调用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>

http://www.schillmania.com/projects/soundmanager2/

SoundManager 2提供了一个易于使用的API,允许声音在任何现代浏览器中播放,包括IE 6+。如果浏览器不支持HTML5,那么它可以从flash中获得帮助。如果你想严格使用HTML5而不使用flash,这里有一个设置,preferFlash=false

它在iPad、iPhone (iOS4)和其他支持html5的设备+浏览器上支持100%无flash音频

使用简单如下:

<script src="soundmanager2.js"></script>
<script>
    // where to find flash SWFs, if needed...
    soundManager.url = '/path/to/swf-files/';

    soundManager.onready(function() {
        soundManager.createSound({
            id: 'mySound',
            url: '/path/to/an.mp3'
        });

        // ...and play it
        soundManager.play('mySound');
    });
</script>

这里有一个实际的演示:http://www.schillmania.com/projects/soundmanager2/demo/christmas-lights/

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