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

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


当前回答

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/

其他回答

根据安全要求,用户必须与网页进行交互才能允许音频,这就是我的做法,基于阅读许多文章,包括在这个网站上

在html中定义所需的音频文件 有一个带有点击的开始游戏按钮 当按钮被点击,然后播放和暂停所有的音频文件,除了一个你想在开始播放

因为所有的音频文件都是在同一个OnClick上“播放”的,你现在可以在游戏中的任何时间不受限制地播放它们

注意,为了最好的兼容性,不要使用wav文件,MS不支持它们

使用mp3和ogg,可以覆盖所有设备

例子:

<audio id="welcome">
    <source src="URL/welcome.ogg" type="audio/ogg">
    <source src="URL/welcome.mp3" type="audio/mpeg">
    Your browser does not support the audio element.
</audio>

根据需要重复游戏中的所有音频

然后:

document.getElementById("welcome").play();
document.getElementById("welcome").pause();

重复需要,但不要暂停你想听到的音频时,游戏开始

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/

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

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

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

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

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

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

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