Skip to content Skip to sidebar Skip to footer

How Can I Play A Random Sound On Click In A Web Page?

I want a random sound to play on a click on a button on a web page. I have researched it quite a bit and this discussion has helped me most: http://www.elated.com/forums/topic/5196

Solution 1:

Use JavaScript to Add Sound

Place the following script in the <head> of your HTML document:

<script language="javascript" type="text/javascript">
 function playSound(soundfile) {
 document.getElementById("dummy").innerHTML="<embed src=\""+soundfile+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
 }
 </script>

The Sound is Placed in an Empty Span

The JavaScript places an embed tag inside an empty span tag when the script is initiated. So, you need to add the following span file somewhere within the body of your HTML page, preferabl near the top of the document:

<span id="dummy"></span>

Call the Script with an onmouseover or onclick Attribute

The last thing you need to add is an element that you want to generate the sound on click or on mouseover. Call the script with one of those attributes:

<ahref="#"onclick="playSound('URL to soundfile');">Click here to hear a sound</a><ponmouseover="playSound('URL to soundfile');">Mouse over this text to hear a sound</p>

Solution 2:

If you have the ID of your audio element, you can do this :

document.getElementById(theId).play();

The audio element could look like this :

<audio id="someId">
    <source src=sound/zbluejay.wav>
</audio>

And if you need it, you may add the audio element dynamically like this :

document.write("<audio id=someId><source src=yourURL</audio>");
document.getElementById('someId').play();​​​​

Fiddle here.

Solution 3:

Haven't tested this one but I guess it should work. I basically select a random String from the array and put an embed-element into the div with the id "element" which then starts the sound.

<script>functionplaySound() {
  var sounds = newArray(
    "http://www.mysite.com/1.wav",
    "http://www.mysite.com/2.wav",
    "http://www.mysite.com/3.wav"
  );

$.("#element").html("<embed src=\""+Math.floor(Math.random()*(sounds.length+1))+"\" autostart=\"true\" />");

}
</script>

edited: i tested this one:

<html><head><scripttype="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script><script>functionplaySound() {
  var sounds = newArray(
    "file:///X:/test.mp3"
  );

$("#element").html("<embed src=\""+sounds[Math.floor(Math.random()*(sounds.length+1))]+"\" hidden=\"true\" autostart=\"true\" />");
}
</script></head><bodyonload="javascript:playSound()"><divid="element"></div></body></html>

Post a Comment for "How Can I Play A Random Sound On Click In A Web Page?"