Background: I have a simple test application which plays a sound using Java's javax.sound.sampled
package. Presently, the application plays the sound for either 10 seconds, or however many times I've told it to loop (whichever comes first). When either of these conditions are reached, the program orders the audio clip to stop playing, and the program should, at that point, completely shut down.
The problem: Oddly, while testing the application on my Raspberry PI, when the end of the program is reached, the audio does not cease; it continues playing for a seemingly arbitrary amount of time afterwards, from a few seconds, up to a minute (perhaps more, I haven't explicitly timed it).
However, the application behaves perfectly fine locally. I'm developing on a Mac, and packaging up a runnable jar which I deployed on the Pi.
Here is a condensed version of the test application code:
public class AudioTest {
public static void main(String[] args) throws UnsupportedAudioFileException, IOException, LineUnavailableException, InterruptedException {
URL audioFileURL = AudioTest.class.getResource("/smokealarm.wav");
if(audioFileURL != null){
System.out.println("Got the file!");
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(audioFileURL);
Line.Info lineInfo = new Line.Info(Clip.class);
Line line = AudioSystem.getLine(lineInfo);
Clip clip = (Clip)line;
clip.open(audioInputStream);
clip.loop(Clip.LOOP_CONTINUOUSLY);
clip.start();
long startTime = System.currentTimeMillis();
int repeatDuration = 10; // repeat for 10 seconds
String previousDuration = null;
do{
Thread.sleep(50); // keeps the application alive
System.out.println("Still waiting...");
}while(clip.isRunning() && ((System.currentTimeMillis() - startTime) < (repeatDuration * 1000)));
System.out.println("Stopping audio");
clip.stop();
// These two lines don't seem to have any effect.
// Adding them here to show that I've attempted them.
clip.flush();
clip.close();
}else{
System.err.println("COULD NOT FIND THE FILE!");
}
}
}
Note: You can obtain the smoke alarm sound file here, or just substitute your own if you prefer
In either case, I know the program has reached the end because I see the "Stopping audio" line in the console.
I cannot think of any reason for this behaviour, other than a bug in the JVM. Has anyone encountered something like this?
P.S: I used this as a guide for writing the above, in case anyone is wondering. Also, I'm using Oracle Java 1.7.