我正在使用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/

其他回答

添加一个隐藏的<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 song = new Audio();
song.src = 'file.mp3';
song.play();

我有一些问题与播放音频,特别是因为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 )

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

你可以使用Web Audio API来播放声音。有相当多的音频库,如嚎叫.js, soundjs等。如果你不担心旧的浏览器,那么你也可以查看http://musquitojs.com/。它提供了一个简单的API来创建和播放声音。

例如,要播放一个声音,你所要做的就是。

import $buzz from 'musquito';

const buzz = $buzz('gunfire.mp3');

buzz.play();

该库还支持音频精灵。