Drew Noakes
Drew Noakes

Reputation: 311315

Reusing an HTML5 Audio object for repeated playing of the same mp3 sound effect

In a simple HTML5/WebGL app, I want to play a sound effect occasionally.

Currently I have in a constructor:

this.audio = new Audio('audio/zeep.mp3');

Then later, I want to play the file:

this.audio.play();

It works the first time, but second plays fail. I've tried resetting the currentTime to zero, and also to 0.1. Neither work:

this.audio.currentTime = 0;
this.audio.play();

If I recreate the Audio object with each time I want to play it, Chrome's network tab shows that it's going across the wire to re-fetch the file, rather than serving it from the cache.

Note that I don't need the same sound effect to play multiple times concurrently. This sound will be infrequent.

Am I missing something here?

Upvotes: 5

Views: 1647

Answers (1)

C19
C19

Reputation: 758

audio element Can't play again.

the http header of the audio file need to have Content-Range like:

Content-Range:bytes 0-5151/5152

it's designed for seeking.

and one audio element can NOT be playing concurrently, if need concurrency.use:

var copy = audio.cloneNode(); copy.play();

Upvotes: 1

Related Questions