javascript Audio object vs. HTML5 Audio tag
audio, html, javascript
Solution
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();
Problem
In a project recently when I loaded a sound with ``` var myAudio = new Audio("myAudio.mp3"); myAudio.play(); ``` It played fine unless a dialogue was opened (ie alert, confirm). However when I instead tried adding an audio tag in my html ``` <audio id="audio1"> <source src="alarm.mp3" type="audio/mpeg" /> </audio> ``` and using ``` var myAudio1 = document.getElementById("audio1"); myAudio1.play() ``` it continued to play after a dialogue was opened. Does anyone know why this is? Also more generally what are the differences between the two ways to play sounds?