在html5中,我可以强制浏览器下载我正在使用的音频文件吗?

时间:2022-10-22 14:53:23

I'm programming html5 games, and using audio files like this

我正在编写html5游戏,并使用这样的音频文件

var sound = new Audio('sound.mp3');

when the command sound.play() appears at some point in the game the browser downloads and plays sound.mp3. this causes a delay in playing the sound on it's first appearance.

当命令sound.play()出现在游戏中的某个点时,浏览器会下载并播放sound.mp3。这导致在首次出现时播放声音的延迟。

is there a way to force the browser to download all the audio files in advance to prevent this?

有没有办法强制浏览器提前下载所有的音频文件,以防止这种情况?

1 个解决方案

#1


2  

var sound = new Audio();

sound.preload = 'auto';

sound.addEventListener('canplaythrough', function () {
    sound.play(); // or other callback actions after preloading
});

document.body.appendChild(sound);

sound.src = 'sound.mp3';
sound.load();

#1


2  

var sound = new Audio();

sound.preload = 'auto';

sound.addEventListener('canplaythrough', function () {
    sound.play(); // or other callback actions after preloading
});

document.body.appendChild(sound);

sound.src = 'sound.mp3';
sound.load();