Note that there are some explanatory texts on larger screens.

plurals
  1. POLine listener event is lost
    primarykey
    data
    text
    <p>I try to play a signal using the Java clip object. I start the clip, then I wait for the STOP event to be fired until I continue the thread. I observed that if I exit the calling thread, which may happen in my application, the sound does not play or only plays the first part. </p> <p>This works fine most of the time, however, every about 50th time, neither the START nor the STOP event is fired, which causes the current thread to wait forever. </p> <p>The question now is, did I do something wrong with the synchronisation which make me loose the events? </p> <pre><code>private static volatile boolean isPlaying = false; private static final Object waitObject = new Object(); public static void playClip(...) ... Clip clip = (Clip) AudioSystem.getLine(...); clip.addLineListener(new LineListener() { public void update(LineEvent event) { if (event.getType() == LineEvent.Type.STOP) { event.getLine().close(); synchronized (waitObject) { isPlaying = false; waitObject.notifyAll(); } } } }); // start playing clip synchronized (waitObject) { isPlaying = true; } clip.start(); // keep Thread running otherwise the audio output is stopped when caller thread exits try { while (isPlaying) { synchronized (waitObject) { waitObject.wait(); } } } catch (InterruptedException e) { e.printStackTrace(); } } </code></pre> <p>Here is the new version using <code> CountDownLatch</code>:</p> <pre><code>private static volatile CountDownLatch playingFinished = new CountDownLatch(1); public static void playClip(...) ... Clip clip = (Clip) AudioSystem.getLine(...); clip.open(audioInputStream); // use line listener to take care of synchronous call clip.addLineListener(new LineListener() { public void update(LineEvent event) { if (event.getType() == LineEvent.Type.STOP) { event.getLine().close(); playingFinished.countDown(); } } }); clip.start(); try { playingFinished.await(); } catch (InterruptedException e) { e.printStackTrace(); } playingFinished = new CountDownLatch(1); </code></pre> <p><br> I didn't include the debugging statements, but they indicate that the thread hangs in <code>playingFinished.await();</code> because the STOP event was not fired and <code>playingFinished.countDown();</code> is never called.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload