关于java AudioInputStream播放短音频没声音的问题

参考java官网关于此问题的解释

播放短的音频时,在还没有播放时,程序就调用了stop事件,解决方法,为Clip添加一个监听器:

 1 import javax.sound.sampled.*;
 2 
 3 public class EarlyStopDemo {
 4     private Clip clip;
 5     
 6     public void go() throws Exception {
 7         AudioInputStream audioInputStream =
 8             AudioSystem.getAudioInputStream(
 9                 new java.io.File("testLong.wav"));
10         DataLine.Info info =
11                 new DataLine.Info(Clip.class, audioInputStream.getFormat());
12         clip = (Clip) AudioSystem.getLine(info);
13         clip.addLineListener(new LineListener() {
14                 public void update(LineEvent e) {
15                     if (e.getType() == LineEvent.Type.STOP) {
16                         synchronized(clip) {
17                             clip.notify();
18                         }
19                     }
20                 }
21             });
22         clip.open(audioInputStream);
23         clip.start();
24         synchronized (clip) {
25             clip.wait();
26         }
27         clip.close();
28     }
29 
30     public static void main(String[] args) throws Exception {
31         EarlyStopDemo acd = new EarlyStopDemo();
32         for (int i = 0; i < 10 ; i++ ) {
33             acd.go();
34         }
35     }
36 }

 

posted @ 2017-04-03 17:35  ~的星辰大海  阅读(3351)  评论(0编辑  收藏  举报