Javascript play sound (wav, MP3, etc) in one line
January 7th, 2010
Alright, enough with the 10 page tutorials from 2006 describing detailed browser-specific implementation tricks to get sound playing. Google needs a refresh. In my experience in the 2010’s, here’s all you need to do to make a simple sound play in your web page:
Step one: add an element to your page
<div id="sound_element"></div>
Step two: play a sound via that element
document.getElementById("sound_element").innerHTML= "<embed src='"+sound_file_url+"' hidden=true autostart=true loop=false>";
Or, if you’re using jQuery:
$('#sound_element').html( "<embed src='"+sound_file_url+"' hidden=true autostart=true loop=false>");
I’ve tried it in Firefox, Chrome and IE and it works like a charm for me. I’d imagine that your user has to have some basic sound software installed in their computer, but at this point, I’d reckon 99% of users do.
Feel free to add to the comments if you find any embellishments necessary to get this working.

thanks!!
But it doesn’t work for Opera and Chrome for OS X in my case. I found a solution here: http://www.scriptwell.net/howtoplaysound.htm
here is code:
var mimeType = “application/x-mplayer2″; //default
var agt = navigator.userAgent.toLowerCase();
function getMimeType(){
if (navigator.mimeTypes && agt.indexOf(”windows”)==-1)
{
// non-IE, no-Windows
var plugin=navigator.mimeTypes["audio/mpeg"].enabledPlugin;
// Mac/Safari & Linux/FFox
if (plugin)
mimeType=”audio/mpeg”;
}//end no-Windows
return mimeType
}//end function getMimeType
mimeType = getMimeType();
function playSound(){
soundElement.innerHTML= “”;
}
Hi,
I found a even more simple solution:
<audio>
<source src=/music/song.ogg>
<source src=/music/song.mp3>
<embed src=/music/song>
</audio>