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="https://stackoverflow.com/questions/21463752/alarm.mp3"
audio.play();

Leave a Comment