how can I wait for a java sound clip to finish playing back?

后端 未结 5 1804
闹比i
闹比i 2020-11-29 10:00

I am using the following code to play a sound file using the java sound API.

    Clip clip = AudioSystem.getClip();
    AudioInputStream inputStream = AudioS         


        
5条回答
  •  有刺的猬
    2020-11-29 10:11

    I prefer this way in Java 8:

    CountDownLatch syncLatch = new CountDownLatch(1);
    
    try (AudioInputStream stream = AudioSystem.getAudioInputStream(inStream)) {
      Clip clip = AudioSystem.getClip();
    
      // Listener which allow method return once sound is completed
      clip.addLineListener(e -> {
        if (e.getType() == LineEvent.Type.STOP) {
          syncLatch.countDown();
        }
      });
    
      clip.open(stream);
      clip.start();
    }
    
    syncLatch.await();
    

提交回复
热议问题