Java检测声音何时停止

时间:2014-12-20 14:07:38

标签: java audio

你好我的应用程序有一个声音类,当我告诉它时它会发出一定的声音。我希望能够检测到声音播放完毕的时间,这样我就可以播放不同的声音,而不是它们重叠,这是我的声音类:

public class Sound {

public static final Sound cash = new Sound("/cash.wav");
public static final Sound snap = new Sound("/snap.wav");
public static final Sound disarm = new Sound("/disarm.wav");
public static final Sound tp = new Sound("/tp.wav");
public static final Sound select = new Sound("/selectBTN.wav");
public static final Sound scroll = new Sound("/btn.wav");
public static final Sound fire = new Sound("/fire2.wav");

private AudioClip c;

public Sound(String filename) {
    try {
        c = Applet.newAudioClip(Sound.class.getResource(filename));

    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void play() {
    try {
        new Thread() {
            public void run() {
                if (!title.mute) {

                    c.play();
                }
            }
        }.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

然后播放声音我使用这行代码:

   Sound.cash.play();

如何检测声音何时播放

1 个答案:

答案 0 :(得分:1)

尝试这样的事情(是一种近似值),使用Line Listener来检测播放的结束:

    import javax.sound.sampled.AudioInputStream;
    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.Clip;
    import javax.sound.sampled.LineEvent;
    import javax.sound.sampled.LineEvent.Type;
    import javax.sound.sampled.LineListener;

    public class Sound {


        private Clip                    c;

        public Sound(final String filename) {
            try {
                c = AudioSystem.getClip();
                final AudioInputStream inputStream = AudioSystem.getAudioInputStream(Sound.class.getResourceAsStream(filename));
                c.open(inputStream);
                c.addLineListener(new LineListener() {

                    @Override
                    public void update(final LineEvent event) {
                        if (event.getType().equals(Type.STOP)) {
                            System.out.println("Do something");
                        }
                    }
                });
            } catch (final Exception e) {
                e.printStackTrace();
            }
        }

        public void play() {
            c.start();
        }

        public static void main(final String[] args) throws InterruptedException {
            final Sound s = new Sound("/cash.wav");
            s.play();
            Thread.sleep(100000);
            final Sound p = new Sound("/cash.wav");
            p.play();
            Thread.sleep(10000);
        }
    }