How to preload a sound in Javascript?

前端 未结 6 1669
伪装坚强ぢ
伪装坚强ぢ 2020-11-27 13:15

I can preload images easily thanks to the onload function. But it doesn\'t work with audio. Browsers like Chrome, Safari, Firefox, etc. don\'t support the

6条回答
  •  清酒与你
    2020-11-27 13:40

    Your problem is that Audio objects don't support the 'load' event.

    Instead, there's an event called 'canplaythrough' that doesn't mean it's fully loaded, but enough of it is loaded that at the current download rate, it will finish by the time the track has had enough time to play through.

    So instead of

    audio.onload = isAppLoaded;
    

    try

    audio.oncanplaythrough = isAppLoaded;
    

    Or better yet.. ;)

    audio.addEventListener('canplaythrough', isAppLoaded, false);
    

提交回复
热议问题