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

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


当前回答

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

其他回答

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

像这样:

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

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

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

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/

const playAudio = (path) => {
   new Audio(path ?? 'defaultPath').play()
}
    
playAudio('path')`
var song = new Audio();
song.src = 'file.mp3';
song.play();

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