我如何一次播放两个声音?

时间:2012-03-11 15:55:11

标签: java audio applet javasound

当我尝试在applet中同时播放两个声音时,它将无法正常工作。我正在使用AudioClip s。甚至可以在小程序中一次播放两个声音吗?

1 个答案:

答案 0 :(得分:2)

从Java 1.3+开始,使用Java Sound API的Clip类。它类似于基于applet的AudioClip类,但更好。

E.G。改编自Java Sound info. page上显示的那个。

import java.net.URL;
import javax.swing.*;
import javax.sound.sampled.*;

public class LoopSounds {

    public static void main(String[] args) throws Exception {
        URL url = new URL(
            "http://pscode.org/media/leftright.wav");
        Clip clip = AudioSystem.getClip();
        AudioInputStream ais = AudioSystem.
            getAudioInputStream( url );
        clip.open(ais);

        URL url2 = new URL(
            "http://pscode.org/media/100_2817-linear.wav");
        Clip clip2 = AudioSystem.getClip();
        AudioInputStream ais2 = AudioSystem.
            getAudioInputStream( url2 );
        clip2.open(ais2);

        // loop continuously
        clip.loop(Clip.LOOP_CONTINUOUSLY);
        clip2.loop(Clip.LOOP_CONTINUOUSLY);
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // A GUI element to prevent the Clip's daemon Thread
                // from terminating at the end of the main()
                JOptionPane.showMessageDialog(null, "Close to exit!");
            }
        });
    }
}