Section 26
USING JAVASCRIPT TO PLAY RANDOM MUSIC/SOUNDS
Here is an example of how you could use JavaScript to randomly select
and play a music/sound file:
<SCRIPT LANGUAGE="JavaScript">
song = new Array(2);
song[0] ='albundy.mid'
song[1] ='addamsfm.mid'
song[2] ='709-obla.mid'
index = Math.floor(Math.random() * song.length);
if (navigator.appName=="Microsoft Internet Explorer")
document.write("<BGSOUND SRC="+song[index]+">")
if (navigator.appName=="Netscape")
document.write("<EMBED SRC="+song[index]+" hidden=true autostart=true");
document.write(" loop=false>")
</SCRIPT>
<NOSCRIPT>
You do not appear to have JavaScript enabled and may not hear the
background sound. Sorry.
</NOSCRIPT>
Although this example only uses three sound files, you can add more
to the list by adding in more song[n] = 'filename.ext' lines. Just be
sure to change the 2 in the "song = new Array(2);" line to the same number
as the last one you use in your list. Also, notice that the numbering
starts with zero for the first sound file.
A WARNING ABOUT THE NETSCAPE JAVASCRIPT LINE IN THE ABOVE EXAMPLE
Unlike HTML code, JavaScript is picky about splitting lines and the
extra line feed/carriage return can confuse it. I've modified the above
code (and hopefully it will still work for you) to allow all the lines to
stay within less than 80 characters across. My hope here is that you
should be able to copy and paste the above section (and edit the "song[n]
parts as mentioned) and it will still work for you. If it doesn't work for
you then try this:
After the line with "Netscape" the next line with document.write should
all be on one line (with document.write as the first part and then
including the part listed below (ALL ON THE SAME LINE WITH document.write):
("<EMBED SRC="+song[index]+" hidden=true autostart=true loop=false>")
I won't run (play) an example music file on this web page because
too many of my other web pages are already cluttered with music/sounds.
[Previous Section]
[Table of Contents]
[Addendum]
[Milt's Micro Digest Home Page]
[Next Section]
The names Microsoft, Internet Explorer, Netscape, and others used in this document
are Trademarks, or Registered Trademarks of the companies represented.
E-mail questions, comments, or suggestions to: miltst@hotmail.com
© 1999 miltst@hotmail.com

(This page was last modified on: Monday, February 08, 1999)