Download this source file
001 package com.wpollock.playsnd;
002
003 import java.applet.*;
004 import java.awt.*;
005 import java.lang.ref.*;
006 import java.util.*;
007
008 /** This applet provides a public "play" method that plays a sound which can
009 * be called from JavaScript in the web page. In addition a cache is
010 * kept of previously played sounds.
011 *
012 * To use this applet you need something like this in your HTML file:<pre>
013 <applet name="playSnd" height="0" width="0"
014 code="com.wpollock.playsnd.PlaySnd.class"
015 archive="PlaySnd.jar">
016 <param name="scriptable" value="true">
017 </applet>
018 <p> A horse says
019 <a href="#"
020 onClick="document.playSnd.play('whinny.wav'); return false;"
021 title="Click to play sound of a horse">neigh</a>.
022 </p>
023 * </pre>
024 *
025 * @author Wayne Pollock, Tampa Florida USA.
026 * @version 1.0
027 * @since 08/08/2004
028 */
029
030 public class PlaySnd extends Applet
031 {
032 private HashMap cache = new HashMap();
033
034 public void start ()
035 {
036 // Pre-load the audio classes to make first sound selected play faster.
037 // This is done by playing a tiny silent sound file bundled with the
038 // applet:
039 getAudioClip( getClass().getResource( "silent.wav" ) ).play();
040 }
041
042 /**
043 * Plays a sound. Implements a cache of previously loaded sounds.
044 *
045 * @param sndName The filename or pathname to the sound file, relative to
046 * this applet's JAR file. (ex: "foo.wav", "audio/foo.wav",
047 * "../media/foo.wav".)
048 */
049
050 public void play ( String sndName )
051 {
052 if ( sndName == null || sndName.length() == 0 )
053 { System.err.println( " PlaySnd.play(): Illegal argument " +
054 "(need sound file name)\n" );
055 return; // Nothing to do
056 }
057
058 AudioClip snd = null;
059
060 if ( cache.containsKey( sndName ) )
061 { SoftReference sr = (SoftReference) cache.get( sndName );
062 snd = ( sr == null ? null : (AudioClip) sr.get() );
063 }
064 else
065 { // Since the applet will be deployed from a JAR, using
066 // getClass().getResource( sndName ) would not work correctly.
067 showStatus( "Loading audio file..." );
068 snd = getAudioClip( getCodeBase(), sndName );
069 if ( snd == null )
070 System.err.println( "PlaySnd.play(): Cannot load sound file \"" +
071 sndName + "\".\n" );
072 }
073 if ( snd != null )
074 { snd.play();
075 showStatus( "" );
076 cache.put( sndName, new SoftReference( snd ) );
077 } else
078 { showStatus( "ERROR! Cannot play sound \"" + sndName + "\"!" );
079 }
080 }
081 }