Javascript &HTML5 中的音频 - 第一次“播放()"调用后延迟 [英] Javascript & audio in HTML5 - Delay after the first 'play()' call

查看:42
本文介绍了Javascript &HTML5 中的音频 - 第一次“播放()"调用后延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个非常简单的 HTML5 + Javascript 代码有问题.它尝试在加载后直接播放声音.

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>

如您所见,我正在加载带有 HTML5 音频标签的声音.声音完全加载后,将启动事件onloadeddata"并执行 Javascript 代码.此代码会提示一个警告窗口并立即开始播放声音.alert() 调用用于直观地通知我声音已成功加载.

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.

但这里有问题: play() 调用有效,但声音在 alert() 窗口出现后几秒钟播放.这种延迟对我来说是有问题的,因为我想要一个指示器来告诉我声音何时可以立即播放.而onloadeddata"似乎不符合这些要求.

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.

请注意,一旦第一个 play() 成功,我在进一步的 play() 调用中不会遇到任何延迟.我可以通过再玩一次!"来验证这一点.button : 点击按钮后立即播放声音,第一个 play() 已经过去.

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.

谁能告诉我在第一次调用 play() 时是否有解决此延迟的方法?或者有什么方法可以告诉我什么时候可以真正播放声音?

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 ?

我使用的是 Google Chrome.

I'm on Google Chrome.

非常感谢!

推荐答案

好吧,问题其实已经很好定义了.

Ok the problem is actually well defined.

  • 此错误仅在 chrome 上发生(Firefox 无问题)
  • 它只涉及 wav 文件
  • 这与 Javascript 的 play() 函数无关,我只需在 chrome 中直接打开 wav 文件即可获得相同的延迟

我仍然没有找到如何解决这个延迟,现在我真的不在乎.我将使用 MP3 或 OGG 文件,这样就足够了.

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.

干杯!

这篇关于Javascript &amp;HTML5 中的音频 - 第一次“播放()"调用后延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆