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

后端 未结 5 1915
闹比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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 10:25

    A sound clip is a type or Line and therefore supports Line listeners.

    If you use addLineListener, you should get events when play starts and stops; if you're not in a loop, you should get a stop when the clip ends. However, as with any events, there might be a lag before the actual end of playback and the stopping.

    Making the method wait is slightly trickier. You can either busy-wait on it (not a good idea) or use other synchronization mechanisms. I think there is a pattern (not sure about it) for waiting on a long operation to throw a completion event, but that's a general question you may want to post separately to SO.

提交回复
热议问题