pfoof
pfoof

Reputation: 195

Java Sound Clip fails to play after multiple plays

I use Clips in a game. The clips play fine, but after some "shots", the following problem occurs

Exception in thread "PulseAudio Eventloop Thread" java.lang.IllegalStateException: drain failed at org.classpath.icedtea.pulseaudio.EventLoop.native_iterate(Native Method) at org.classpath.icedtea.pulseaudio.EventLoop.run(EventLoop.java:133) at java.lang.Thread.run(Thread.java:724)

My code:

public static Clip[] sounds;
...
sounds = new Clip[3];
sounds[0] = getClip("gun.wav");
sounds[1] = getClip("click.wav");
sounds[2] = getClip("over.wav");
...
private void playSound(Clip clp) {
        final Clip clip = clp;
        Runnable soundPlayer = new Runnable() {

            @Override
            public void run() {
                try {
                    if(clip.isActive() || clip.isRunning()) clip.stop();
                    clip.setMicrosecondPosition(0);
                    clip.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        new Thread(soundPlayer).start();
}
public void shoot() { //runs when space is clicked 
if(canShoot) playSound(sounds[0]);
}

Upvotes: 1

Views: 1178

Answers (2)

phreakhead
phreakhead

Reputation: 15239

So I had a similar problem on OS X, where the clip was sometimes not playing if you tried to stop it and restart it from the beginning. I fixed it by calling flush() right after stop():

if(clip.isActive() || clip.isRunning()) {
    clip.stop();
    clip.flush();
}

Upvotes: 1

Mike Clark
Mike Clark

Reputation: 10136

You shouldn't need to spawn a background thread to interact with the Clip. The most commonly used methods of Clip, like "start" and "stop" operate asynchronously, meaning they do not block, so it should be okay to call them from the GUI/AWT/Swing thread.

This page has some reasonable examples: http://www3.ntu.edu.sg/home/ehchua/programming/java/J8c_PlayingSound.html

I see you are using IcedTea and PulseAudio. You may experience different behavior when using javax.sound in this JVM, as opposed to the Oracle JVM, since the implementations of javax.sound are significantly different between these two products.

Upvotes: 0

Related Questions