Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

java - Play audio clips sequentially in JApplet

I'm trying to play audio clips sequentially, but they all play at the same time. I'm not sure what I am doing wrong. Could you Please help. I'm using JFrame, and this code is giving runtime error.

AudioClip click;
AudioClip click2;

URL urlClick1 = DisplayMath.class.getResource("number11.wav");
click = Applet.newAudioClip(urlClick1);

URL urlClick2 = DisplayMath.class.getResource("number12.wav");
click2 = Applet.newAudioClip(urlClick2);

click.play();
click.notify();

try {
    click2.wait();
} 
catch (InterruptedException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}
click2.play();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The functionality you are wanting to implement is not possible with an AudioClip, but is it with a Clip to which a LineListener is attached. See this example which flips between 2 clips.

import javax.sound.sampled.LineListener;
import javax.swing.*;

class TwoClips {

    public static void main(String[] args) throws Exception {
        URL url1 = new URL("http://pscode.org/media/100_2817-linear.wav");
        URL url2 = new URL("http://pscode.org/media/leftright.wav");
        final Clip clip1 = AudioSystem.getClip();
        clip1.open(AudioSystem.getAudioInputStream(url1));
        final Clip clip2 = AudioSystem.getClip();
        clip2.open(AudioSystem.getAudioInputStream(url2));
        LineListener listener = new LineListener() {

            Clip currentClip = clip1;

            @Override
            public void update(LineEvent event) {
                if (event.getType() == LineEvent.Type.STOP) {
                    if (currentClip == clip1) {
                        currentClip = clip2;
                    } else {
                        currentClip = clip1;
                    }
                    currentClip.setFramePosition(0);
                    currentClip.start();
                }
            }
        };
        clip1.addLineListener(listener);
        clip2.addLineListener(listener);
        Runnable r = new Runnable() {

            @Override
            public void run() {
                clip1.start();
                JOptionPane.showMessageDialog(null, "Close me to exit!");
            }
        };
        // Swing GUIs should be created and updated on the EDT
        // http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
        SwingUtilities.invokeLater(r);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...