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/
One poster recommended making a Javascript function to run whenever the button is clicked, as follows:
<script>
function playSound() {
var sounds = [
"http://www.mysite.com/1.wav",
"http://www.mysite.com/2.wav",
"http://www.mysite.com/3.wav"
];
**// Choose a random sound here and play it**
}
</script>
I understand the part about making an array of sounds. I think I have the part about selecting a random array element figured out. I am just stuck on how to play a sound inside the JS function as the poster recommends. Can I use an HTML5 audio tag inside the JS function?
I don’t care whether the code for actually playing the file is inside or outside the function. Actually, I was first going to use JS just to randomly select an element, then have a line of HTML play the element of the array returned by the JS function. I gave up on that because I couldn’t figure out how to specify that I wanted to play the return value of a JS function in HTML.
Thank you.
Use JavaScript to Add Sound
Place the following script in the
<head>of your HTML document: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:
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: