I have code that plays sound from a .wav file, but I have no way of stopping the song, or even quitting the program until it ends. As this is a 5 minute song, this is a problem. Here is the code for how I play the wav:
public class EasySound{
private SourceDataLine line = null;
private byte[] audioBytes;
private int numBytes;
public EasySound(String fileName){
File soundFile = new File(fileName);
AudioInputStream audioInputStream = null;
try {
audioInputStream = AudioSystem.getAudioInputStream(soundFile);
} catch (Exception ex) {
System.out.println("*** Cannot find " + fileName + " ***");
System.exit(1);
}
AudioFormat audioFormat = audioInputStream.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class,
audioFormat);
try {
line = (SourceDataLine)AudioSystem.getLine(info);
line.open(audioFormat);
} catch (LineUnavailableException ex) {
System.out.println("*** Audio line unavailable ***");
System.exit(1);
}
line.start();
audioBytes = new byte[(int)soundFile.length()];
try {
numBytes = audioInputStream.read(audioBytes, 0, audioBytes.length);
} catch (IOException ex) {
System.out.println("*** Cannot read " + fileName + " ***");
System.exit(1);
}
}
public void play() {
line.write(audioBytes, 0, numBytes);
}
}
Is there a better way to do this, or a way to do this that would allow me to stop the song mid-play?
Thanks in advance!