Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Audio Looping

I've been playing with HTML5 audio recently, and though I can get it to play the sound it only ever will play once. No matter what I try (setting the properties, event handlers, etc) I can't seem to get it to loop.

Here's the basic code I'm using:

//myAudio is declared at a global scope, so it doesn't get garbage collected. myAudio = new Audio('someSound.ogg'); myAudio.loop = true; myAudio.play(); 

I'm testing using Chrome (6.0.466.0 dev) and Firefox (4 beta 1), both of which seem happy to ignore my requests for looping. Any ideas?

UPDATE: The loop property is now supported in all major browsers.

like image 902
Toji Avatar asked Jul 17 '10 22:07

Toji


People also ask

How do you repeat audio in HTML?

The loop attribute on an <audio> tag specifies that the audio file will play repeatedly.

What is audio repeat attribute?

Definition and Usage. The loop attribute is a boolean attribute. When present, it specifies that the audio will start over again, every time it is finished.


2 Answers

While loop is specified, it is not implemented in any browser I am aware of Firefox [thanks Anurag for pointing this out]. Here is an alternate way of looping that should work in HTML5 capable browsers:

var myAudio = new Audio('someSound.ogg');  myAudio.addEventListener('ended', function() {     this.currentTime = 0;     this.play(); }, false); myAudio.play(); 
like image 185
kingjeffrey Avatar answered Oct 20 '22 15:10

kingjeffrey


To add some more advice combining the suggestions of @kingjeffrey and @CMS: You can use loop where it is available and fall back on kingjeffrey's event handler when it isn't. There's a good reason why you want to use loop and not write your own event handler: As discussed in the Mozilla bug report, while loop currently doesn't loop seamlessly (without a gap) in any browser I know of, it's certainly possible and likely to become standard in the future. Your own event handler will never be seamless in any browser (since it has to pump around through the JavaScript event loop). Therefore, it's best to use loop where possible instead of writing your own event. As CMS pointed out in a comment on Anurag's answer, you can detect support for loop by querying the loop variable -- if it is supported it will be a boolean (false), otherwise it will be undefined, as it currently is in Firefox.

Putting these together:

myAudio = new Audio('someSound.ogg');  if (typeof myAudio.loop == 'boolean') {     myAudio.loop = true; } else {     myAudio.addEventListener('ended', function() {         this.currentTime = 0;         this.play();     }, false); } myAudio.play(); 
like image 32
mgiuca Avatar answered Oct 20 '22 14:10

mgiuca