Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make my Java application with audio play nice in Linux?

Tags:

java

linux

audio

I have a Java application whose UI relies heavily on audio. On Windows and OS X, everything works fine; on Linux, however, the application requires exclusive access to the sound device, a LineUnavailableException is thrown and no sound is heard. I'm using Kubuntu 9.10.

This means that no other application can play audio while the program is running, and can't even be holding an audio device when the program starts. This is naturally unacceptable.

Here is the code I'm using to play audio:

AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);

Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);

clip.start();

this.wait((clip.getMicrosecondLength() / 1000) + 100);

clip.stop();

Am I doing something wrong? Is using Java to play audio in Linux a lost cause?

like image 540
Ville Sundberg Avatar asked Dec 21 '09 17:12

Ville Sundberg


2 Answers

I fear that audio in Linux is a lost cause itself. But in this case, it really is a known Java Bug. You should try to figure out what sound architecture you are using. I think the default for Ubuntu is PulseAudio/ALSA. I'm not not sure about Kubuntu though.

There is a known workaround (I never tried it myself though).

It's also possible that some other applications you're running is exclusively using the soundcard, so make sure to test with different applications (i.e. applications that play nicely with others).

like image 158
sfussenegger Avatar answered Sep 29 '22 10:09

sfussenegger


I was able to play audio sound on GNU/Linux (Ubuntu 10.10) using the OpenJDK with some tweaks. I believe the the LineUnavailableException was a bug in PulseAudio and was fixed in 10.10.

I needed to specify the Format (something not needed on Windows).

AudioInputStream audioIn = AudioSystem.getAudioInputStream(in);

// needed for working on GNU/Linux (openjdk) {
AudioFormat format = audioIn.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip clip = (Clip)AudioSystem.getLine(info);
// }
// on windows, {
//Clip clip = AudioSystem.getClip();
// }

Be aware that the call to Clip.getMicrosecondLength() returns milliseconds.

like image 42
FabienB Avatar answered Sep 29 '22 12:09

FabienB