tags:

views:

102

answers:

1

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:

1) Loading the audio file into a byte array and passing that to clip.open

2) 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: http://bugs.sun.com/bugdatabase/view_bug.do?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?

+2  A: 

I've had great luck with the BASS Audio Library.

It's written natively, so it breaks write-once, run-anywhere, but it will work on Windows, OS/X, and Linux, which is anywhere enough for my needs.

Dean J
Thanks! An external library may be a way to go - I'd prefer to stay all-Java though, if at all possible.
Thomas