PreLoaded Sounds Play on Mouseover

[Total: 0    Average: 0/5]

This example shows how to have some music play on an event.

Head Code:

<script>
var _s=0; /* just a counter - must start at 0 - do not change */
var Sounds = new Array();
    Sounds[_s++] = "/data/tada.wav";  /* add any sound that will be pre-loaded */
    Sounds[_s++] = "/data/rebin.wav"; /* add any sound that will be pre-loaded */
    Sounds[_s++] = "/data/tada.wav";  /* add any sound that will be pre-loaded */
    Sounds[_s++] = "/data/tada.wav";  /* add any sound that will be pre-loaded */

/* Frob below at own risk */
document.write('<BGSOUND ID="soundContainer_IE_DOM">');

/*
 * Browser-Sniffer
 */
var isIE4 = (navigator.appVersion.indexOf("MSIE")!=-1 && document.all)? true:false;
var isNS4 = (navigator.appName=="Netscape" && navigator.plugins["LiveAudio"])? true:false;
var isDOM = document.getElementById?true:false;
var isOK = isIE4||isNS4||isDOM;

onload=PreLoadSounds; /* this will make the pre-loading occur - put in body tag onload="PreLoadMusic()" if you want */

function PreLoadSounds()
{
  if (!isOK)
    return;

  /*
   * This block creates a container-object to hold all the hidden pre-loaded sound objects.
   */
  if (isNS4)
    SoundDiv = new Layer(0,window);
  else
    document.body.insertAdjacentHTML("BeforeEnd","<DIV ID='SoundDiv' STYLE='position:absolute;'></DIV>");

  /*
   * This block writes all the sound objects into the container-object.
   */
  var Str = '';
  for (i=0;i<Sounds.length;i++)
    Str += "<EMBED SRC='"+Sounds[i]+"' AUTOSTART='FALSE' HIDDEN='TRUE'>"

  if(isDOM)
    document.getElementById("SoundDiv").innerHTML=Str;
  else if(isIE4)
    SoundDiv.innerHTML=Str;
  else
  {
    /* must be NS4 */
    SoundDiv.document.open();
    SoundDiv.document.write(Str);
    SoundDiv.document.close();
  }

  /*
   * This finds the object -- we want to set an access method to make it play or stop.
   */
  soundObject = null;
  if(isDOM)
    soundObject = document.getElementById('soundContainer_IE_DOM');
  else if(isIE4)
    soundObject = document.all.soundContainer_IE_DOM;
  else
    soundObject = SoundDiv;
  soundObject.control = auCtrl;
}

function auCtrl(SoundsArrayIndex,play)
{
  if (isIE4||isDOM)
    this.src = play? Sounds[SoundsArrayIndex]:'';
  else
    eval("this.document.embeds[SoundsArrayIndex]." + (play? "play()":"stop()"))
}

function playSound(SoundsArrayIndex) { if (window.soundObject) soundObject.control(SoundsArrayIndex,true); }
function stopSound(SoundsArrayIndex) { if (window.soundObject) soundObject.control(SoundsArrayIndex,false); }
</script>

Body Code:

<A HREF="#"
   onMouseOver="playSound(0)"
   onMouseOut="stopSound(0)">Move mouse over to play sound #1</A>
<BR>
<A HREF="#"
   onMouseOver="playSound(1)"
   onMouseOut="stopSound(1)">Move mouse over to play sound #2</A>

Times Viewed: 10

Leave a Reply

Your email address will not be published. Required fields are marked *