Reliably playing a short sound in Java

后端 未结 6 1430
时光说笑
时光说笑 2021-01-06 04:46

I am tyring to write some Java code that basically just plays a short .wav file - with \'short\' I mean a fraction of a second. (The file I use is at /usr/share/sounds/gener

6条回答
  •  不知归路
    2021-01-06 05:19

    The most straightforward approach here is probably to just get the exact clipLength in milliseconds (rounding up) and use that to sleep the thread playing the sound for the duration. Make sure you use synchronized to avoid IllegalMonitorStateExceptions.

    synchronized(clip){
        clip.start();
        try{
            double clipLength = audioParams.getFrameLength() / 
                                   audioParams.getFormat().getFrameRate();
            clip.wait(java.lang.Math.round(clipLength +.5)*1000);
        } catch (InterruptedException e) {
            System.out.println( e.getMessage() );
        }
    
        c.stop();
     }
    

提交回复
热议问题