javascript Audio object vs. HTML5 Audio tag javascript Audio object vs. HTML5 Audio tag javascript javascript

javascript Audio object vs. HTML5 Audio tag


According to this wiki entry at Mozilla <audio> and new Audio() should be the same but it doesn't look like that is the case in practice. Whenever I need to create an audio object in JavaScript I actually just create an <audio> element like this:

var audio = document.createElement('audio');

That actually creates an audio element that you can use exactly like an <audio> element that was declared in the page's HTML.

To recreate your example with this technique you'd do this:

var audio = document.createElement('audio');audio.src = 'alarm.mp3'audio.play();


JavaScript halts during an Alert or Confirm box.

You cannot concurrently run code and display an alert(), confirm(), or prompt(), it literally waits for user input on this, this is a core feature of JavaScript.

I am assuming it is that very reason why an audio file played entirely within JavaScript scope does this. Comparatively Flash video clips or HTML5 audio/video will continue to play on even when a JavaScript alert/confirm/prompt is open.

As for what method is better, well that is up to you. It is pretty archaic to do anything with the JavaScript built in alert/confirm/prompt anymore, there are way better looking prompts you can make with jQuery UI and so on.

If you have a lot of dynamic content on the page or are you looking into background buffering audio before they need to be triggered and so on, then JavaScript is probably the saner way to go about things.

If you have literally just one player on the screen then there is no excuse for not putting in onto the HTML code. Although unlikely to affect anyone these days, it is still bad practice to rely heavily on JavaScript when there is no reason to.


I came up with the function below from several answers across the web.

function playAudio(url){  var audio = document.createElement('audio');  audio.src = url;  audio.style.display = "none"; //added to fix ios issue  audio.autoplay = false; //avoid the user has not interacted with your page issue  audio.onended = function(){    audio.remove(); //remove after playing to clean the Dom  };  document.body.appendChild(audio);}