package com.hatherly.babykeyboardfun;
import com.sun.media.sound.JavaSoundAudioClip;
import java.applet.Applet;
import java.applet.AudioClip;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.URL;
import javax.swing.ImageIcon;
/**
* This is an implementation of the BabySoundPlayer interface, and does
* the actual playing of the audio clips. This implementation uses the
* standard ausio mechanisms in the Applet API. This is somewhat limited
* but has the advantage of beiong able to play a clip loaded from an
* input stream, and can therefore be used for clips stored in JAR files.
* There is an alternate implementation of the BabySoundPlayer interface
* that uses the Java Media Framework, but that implementation does not
* support loading clips from within JAR files.
*/
public class SoundPlayer_AppletAudio implements BabySoundPlayer {
private String myFileName = "";
private AudioClip clip;
/**
* Creates a new instance of SoundPlayer
* @param soundNumber index for the sound clip
* to load (defined in the Constants class
*/
public SoundPlayer_AppletAudio(int soundNumber) {
try {
String path = "/resources/" + Constants.audioFilenames[soundNumber];
System.out.println("Loading sound from path: " + path);
clip = getAudioClip(path);
} catch (Exception ex) {
System.out.println("Error with sound file: " + this.myFileName);
ex.printStackTrace();
}
}
/**
* Trigger the audio playback
*/
public void makeSound() {
try {
System.out.println("Playing clip");
clip.play();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* This method was added to allow audio clips to be loaded correctly when
* they are inside a JAR file. I found the method for creating an
* AudioClip from an InputStream on this page:
* http://snobol.cs.berkeley.edu/prospector/search?src=java.io.InputStream&dst=java.applet.AudioClip
*/
private static AudioClip getAudioClip(String path) throws IOException {
int MAX_IMAGE_SIZE = 1159000; //Change this to the size of
//your biggest clip, in bytes.
int count = 0;
String filename = SoundPlayer_AppletAudio.class.getResource(path).toString();
System.out.println("Loading audio from file: " + filename);
BufferedInputStream imgStream = new BufferedInputStream(
SoundPlayer_AppletAudio.class.getResourceAsStream(path) );
if( imgStream != null ) {
AudioClip newClip = new JavaSoundAudioClip(imgStream);
try {
imgStream.close();
}
catch( IOException ieo ) {
System.err.println( "Can't close file " + path );
}
return newClip;
}
else {
System.err.println( "Couldn't find file: " + path );
return null;
}
}
}
syntax highlighted by Code2HTML, v. 0.9.1