tags:

views:

108

answers:

1

I have a problem playing a sound correctly in Java using the Clip interface.

Playing the sound works using:

clip = (Clip)mixer.getLine(dataLineInfo);
clip.open(audioFormat, byteData, 0, byteData.length);
clip.start();

However there is a memory leak if clips aren't closed.

I have tried adding a line listener before starting the clip, and use the following code:

public void update(LineEvent e) {
    if (e.getType() == LineEvent.Type.STOP) {
        e.getLine().close();

However, this causes the sound to degrage.

Adding a 1 second sleep in the method makes things work again on my machine - but I would prefer a more elegant solution - I don't think waiting in a listener method is good practice and other machines may take longer.

It is bizarre that the stop event is sent some time arbitrary time prior to the sound stopping.

Does anyone have any ideas on a better way to solve this?

(Related to this, this and this but none are solutions for me)

+1  A: 

This appears to be the symptoms described in bug 4434125.

The suggested solution in that bug comments is to call clip.drain() (in an appropriate thread, because it is a blocking call), and then closing the clip when drain completes (since it will block until the data line's internal buffer is emptied (as per Javadocs for the drain method).

Ash
Thanks - that's the problem. "The old implementation (Java Sound Engine) will not be fixed.". Hence the code now attempts to use the System default mixer.
Pool