PDA

View Full Version : Playing sound with java script



Torben
12-16-2011, 11:36 PM
I wrote the following small HTML page, trying to play a sound in Firefox 8 and Internet Explorer 9. The button and the <a></a> link work fine, but calling from the <script></script> tag does nothing. Does anybody know, what can be wrong, and what I can do? I'm sorry, you have to supply the oef.wav file, since I can't upload it.


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="GENERATOR" content="Mozilla/4.05 [en] (Win95; I) [Netscape]">
<meta name="Author" content="Torben Amtrup">
<title>Soundtest</title>

<script>
function EvalSound(soundobj) {
var thissound=document.getElementById(soundobj);
thissound.Play();
}
</script>
</head>

<body>
<embed src="oef.wav" width="1" height="1" id="sound1" enablejavascript="true" autostart="false">

<form>
<input type="button" value="Play Sound" onclick="EvalSound('sound1')">
</form>

<a onclick="EvalSound('sound1')">Play Sound</a>

<script language="JavaScript">
EvalSound('sound1');
</script>

</body>

hdewantara
12-18-2011, 07:01 AM
Try to give it some microseconds, like:
<script>
setInterval("EvalSound('sound1')",1000);
</script>

I'm not sure why though :D

Philip M
12-18-2011, 01:25 PM
Cross-browser scripting for playing sounds is a nightmare.

http://sodeve.net/2011/10/how-to-add-javascript-beep-that-runs-in-all-browsers/

rnd me
12-19-2011, 04:00 AM
its probably that the sound file has not loaded when the inline <script> tries to play it, whereas by the time you get around to clicking the link/button the file has already loaded and plays just fine.

you might be able to do something like:

<script>
window.onload=function(){
EvalSound('sound1');
};
</script>

if that doesn't work, i would recommend jplayer (a jquery plugin) for (relatively) simple audio playback functionality that works on all browsers and devices like tablets and phones.