package com.wpollock.playsnd; import java.applet.*; import java.awt.*; import java.lang.ref.*; import java.util.*; /** This applet provides a public "play" method that plays a sound which can * be called from JavaScript in the web page. In addition a cache is * kept of previously played sounds. * * To use this applet you need something like this in your HTML file:
      <applet name="playSnd" height="0" width="0"
              code="com.wpollock.playsnd.PlaySnd.class"
              archive="PlaySnd.jar">
         <param name="scriptable" value="true">
      </applet>
      <p> A horse says
      <a href="#"
         onClick="document.playSnd.play('whinny.wav'); return false;"
         title="Click to play sound of a horse">neigh</a>.
      </p>
 * 
* * @author Wayne Pollock, Tampa Florida USA. * @version 1.0 * @since 08/08/2004 */ public class PlaySnd extends Applet { private HashMap cache = new HashMap(); public void start () { // Pre-load the audio classes to make first sound selected play faster. // This is done by playing a tiny silent sound file bundled with the // applet: getAudioClip( getClass().getResource( "silent.wav" ) ).play(); } /** * Plays a sound. Implements a cache of previously loaded sounds. * * @param sndName The filename or pathname to the sound file, relative to * this applet's JAR file. (ex: "foo.wav", "audio/foo.wav", * "../media/foo.wav".) */ public void play ( String sndName ) { if ( sndName == null || sndName.length() == 0 ) { System.err.println( " PlaySnd.play(): Illegal argument " + "(need sound file name)\n" ); return; // Nothing to do } AudioClip snd = null; if ( cache.containsKey( sndName ) ) { SoftReference sr = (SoftReference) cache.get( sndName ); snd = ( sr == null ? null : (AudioClip) sr.get() ); } else { // Since the applet will be deployed from a JAR, using // getClass().getResource( sndName ) would not work correctly. showStatus( "Loading audio file..." ); snd = getAudioClip( getCodeBase(), sndName ); if ( snd == null ) System.err.println( "PlaySnd.play(): Cannot load sound file \"" + sndName + "\".\n" ); } if ( snd != null ) { snd.play(); showStatus( "" ); cache.put( sndName, new SoftReference( snd ) ); } else { showStatus( "ERROR! Cannot play sound \"" + sndName + "\"!" ); } } }