Search code examples
javaaudioappletjavasound

How do I play two sounds at once?


When I try to play two sounds at once in an applet, it won't work. I'm using AudioClips. Is it even possible to play two sounds at once in an applet?


Solution

  • Since Java 1.3+, use the Clip class of the Java Sound API. It is similar to the applet based AudioClip class, but better.

    E.G. adapted from the one shown on the 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!");
                }
            });
        }
    }