的JavaScript + HTML5:音频只在特定情况下打一次 [英] JavaScript + HTML5: Audio will only play once under certain circumstances

查看:129
本文介绍了的JavaScript + HTML5:音频只在特定情况下打一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有时碰到与HTML5音频标签problemes。在某些情况下,加载的音频文件只能播放一次,然后再也没有。

I sometimes run into problemes with the HTML5 audio tag. Under some circumstances, the loaded audio file will only play once and then never again.

HTML(Django模板)

HTML (Django Template)

<audio id="audio" src="{% if key %}streams/{{key}}.wav{% else %}{% endif %}" controls>
    <p>Your user agent does not support the HTML5 Audio element.</p>
</audio>

的JavaScript(用jQuery)

JavaScript (with jQuery)

function sendText() {
    var textfield = $("#textfield"),
        text = textfield.val();

    $.ajax({
        url: '/rec/',
        type: "POST",
        data: JSON.stringify({text: text}),
        success: function(response) {
            var baseUrl = window.location.href.split("?")[0];
            $(location).attr('href', baseUrl + "?s=" + response.key);
        },
        complete: function() {},
        error: function(xhr, textStatus, thrownError) {
            console.log("error");
        }
    });
}

所以我发送一个Ajax请求到服务器,一键搞定回来,然后重新载入页面(通过JavaScript)的密钥参数。然后,该密钥将是在音频标签内装载的wav文件的名称。

So I am sending an Ajax request to the server, get a key back and then reload the page (via JavaScript) with the key as parameter. This key will then be the name of the wav file that is loaded within the audio tag.

一旦加载页面,我可以播放音频,但只有一次。点击播放第二遍,根本不会做任何事情。

As soon as the page is reloaded, I can play audio, but only once. Clicking on play a second time, doesn't do anything at all.

然而,当我点击浏览器的刷新按钮和加载页面的又一时间,一切工作正常。

However, when I click on the browser's reload button and load the page yet another time, everything works fine.

对此有任何的解释?

推荐答案

根据我自己的一些试验和错误,我建议想一旦它发挥到currentTime属性重置为0,并再次尝试。

Based on some of my own trial-and-error, I'd suggest trying to reset the currentTime property to 0 once it has played and try it again.

我发现某些情况下(和你的可能是其中之一),其中音频卡和结束,本身不复位。

I've found some cases (and yours might be one of them) where the audio gets stuck and the end and doesn't reset by itself.

这是实际的解释我不能提供...但如果​​它像我见过的 - 这可能是一个可行的解决方案。

An actual "explanation" I can't offer...but if it's like the ones I've seen - this might be a viable solution.

<audio id="foo"><source url="myaudio.mp3"></audio>
...
var soundFoo = document.getElementById('foo');
soundFoo.play();
soundFoo.onended = function() {
  soundFoo.currentTime = 0;
  soundFoo.play(); // assuming you want it to repeat right away.
}

这篇关于的JavaScript + HTML5:音频只在特定情况下打一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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