basilikum
basilikum

Reputation: 10528

JavaScript + HTML5: Audio will only play once under certain circumstances

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 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 (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");
        }
    });
}

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.

Is there any explaination for this?

Upvotes: 0

Views: 1942

Answers (1)

Ryan Hemphill
Ryan Hemphill

Reputation: 121

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.
}

Upvotes: 1

Related Questions