I am tyring to write some Java code that basically just plays a short .wav file – with ‘short’ I mean a fraction of a second. (The file I use is at /usr/share/sounds/generic.wav for those of you using Ubuntu.)
The problem is, I can’t seem to figure out how to play that sample reliably, i.e., in all my attempts, I can get my program to play the sound in 4 out of 5 times or so, but never 100%.
This is what has worked best so far as a stand-alone program:
File soundFile = new File("/usr/share/sounds/generic.wav");
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(soundFile);
clip.open(inputStream);
clip.start();
(Note that the code doesn’t even call clip.stop()) But even with that one, if I run it a couple of times in a row, sooner or later there will be a run without any sound being played, but no Exceptions either.
Variations I’ve tried:
-
Loading the audio file into a byte array and passing that to clip.open
-
Attaching a LineListener to the clip to wait for STOP events
plus a couple of random try-outs, but so far I haven’t managed to create code that works every time.
I’m also aware of the following bug: https://bugs.java.com/bugdatabase/view_bug?bug_id=4434125 but I’m using Java 1.6 and the report claims that things should be fine with Java 1.5 or later.
Any ideas? Is it PulseAudio?
I suspect now that the reason my test program failed was a timing issue. Either I attempted playing the short sound before the samples were fully loaded, or the program terminated too quickly. The reason for this suspicion is that if I change the above code slightly like so:
then the short sound gets played correctly every time I hit enter.