Javascript & audio in HTML5 - Delay after the first 'play()' call

匆匆过客 提交于 2021-01-28 00:34:40

问题


I have a problem with this very simple HTML5 + Javascript code. It attempts to play a sound directly after it has been loaded.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Test page</title>
    </head>
    <body>

        <audio src="freedom.wav" 
               id="audio1"
               preload='auto' 
               onloadeddata="alert('the sound has been loaded !'); document.getElementById('audio1').play();"
        ></audio>

        <input type="button" value="Play it again !" onclick="document.getElementById('audio1').play();" />

    </body>
</html>

As you can see, I'm loading a sound with the HTML5 audio tag. Once the sound is fully loaded, the event "onloadeddata" is launched and executes the Javascript code. This code prompts an alert window and starts playing the sound immediately. The alert() call is there to visually notify me that the sound has successfully been loaded.

But here is the problem : the play() call works, but the sound is played SECONDS after the apparition of the alert() window. This delay is problematic to me, as I would like to have an indicator that tells me when the sound is actually ready to be played immediately. And it appears that "onloadeddata" doesn't meet those requirements.

Note that once the first play() is successfull, I suffer no delay in further play() calls. I could verify this with the "Play it again!" button : the sound is played immediately after clicking on the button, one the first play() has passed.

Could anyone tell me if there is a solution to this delay at the first call of play() ? Or is there a way that can tell me when the sound can actually be played ?

I'm on Google Chrome.

Thank you very much !


回答1:


Ok the problem is actually well defined.

  • This bug only happens on chrome (no prob with Firefox)
  • It only concerns wav files
  • This has nothing to do with the play() function of Javascript, I get the same delay by simply opening the wav file directly in chrome

I still didn't find how to fix this delay and I don't really care now. I shall use MP3 or OGG files and that's going to be good enough.

Cheers !



来源:https://stackoverflow.com/questions/18360591/javascript-audio-in-html5-delay-after-the-first-play-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!