I am finalizing the first version of my javascript app, and I would like to add sound effects. What is the recommended way to play a short sound (mp3 or wav or other format) using javascript in a web browser? I have ten sounds that I would like to have pre-loaded and able to play during application execution.
I've created this small test app an开发者_JS百科d can't get the audio to play. Maybe someone can show me where I'm going wrong:
<html>
<head>
<title>Sound Test</title>
<script type="text/javascript" src="raphael.js"></script>
</head>
<body>
<div id="debugPane" style="width: 300px; height: 500px; float: left; background-color: #EEEEEE; margin-left: 10px; border-style: solid; border-width: 1px;"></div>
<script type="text/javascript">
try {
var snd = new Audio("mp3/1.mp3");
alert(snd.src);
snd.play();
} catch (err) {
document.getElementById("debugPane").innerHTML += "" + err.message;
}
</script>
</body>
</html>
The correct file is being chosen. However, when I point to a file that doesn't exist, I don't get any exception. The file happily reports what its src is even though it's not actually on my filesystem.
function playSound(soundfile) {
document.getElementById("dummy").innerHTML =
"<embed src='"+soundfile+"' hidden='true' autostart='true' loop='false' />";
}
where dummy is a hidden div somewhere on your page.
It ended up working the whole time in Chrome and Safari in Windows and Mac. My dev box was a Chromium/Ubuntu environment, which either is not supported, or my sound is misconfigured. In fact, it doesn't work in Ubuntu with any browser so far.
精彩评论