Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html5 Audio plays only once in my Javascript code

I have a dashboard web-app that I want to play an alert sound if its having problems connecting. The site's ajax code will poll for data and throttle down its refresh rate if it can't connect. Once the server comes back up, the site will continue working.

In the mean time I would like a sound to play each time it can't connect (so I know to check the server). Here is that code. This code works.

var error_audio = new Audio("audio/"+settings.refresh.error_audio);
error_audio.load();

//this gets called when there is a connection error.
function onConnectionError() {
   error_audio.play();
}

However the 2nd time through the function the audio doesn't play. Digging around in Chrome's debugger the 'played' attribute in the audio element gets set to true. Setting it to false has no results. Any ideas?

like image 548
Poul Avatar asked Oct 27 '25 14:10

Poul


1 Answers

I encountered this just today, after more searching I found that you must set the source property on the audio element again to get it to restart. Don't worry, no network activity occurs, and the operation is heavily optimized.

var error_audio = new Audio("audio/"+settings.refresh.error_audio);
error_audio.load();

//this gets called when there is a connection error.
function onConnectionError() {
   error_audio.src = "audio/"+settings.refresh.error_audio;
   error_audio.play();
}

This behavior is expressed in chrome 21. FF doesn't seem to mind setting the src twice either!

like image 118
Ninjaxor Avatar answered Oct 29 '25 03:10

Ninjaxor