编程语言
首页 > 编程语言> > java – 在JApplet中按顺序播放音频片段

java – 在JApplet中按顺序播放音频片段

作者:互联网

我正在尝试按顺序播放音频片段,但它们都在同一时间播放.我不确定我做错了什么.能否请你帮忙.我正在使用JFrame,这段代码给出了运行时错误.

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();

解决方法:

使用AudioClip无法实现您想要实现的功能,但是它是否附加了LineListener的Clip.请参阅此示例,该示例在两个剪辑之间翻转.

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);
    }
}

标签:javasound,japplet,clip,java,audio
来源: https://codeday.me/bug/20191002/1844877.html