简体   繁体   中英

How could I play two sounds together?

Well, I am writing a gaming project using java and I want to implement something like this : when an object begins to move, it makes some sound effects, and when another object begins to move before the first object stops, it also makes some sound effects. After the second object begins to move and before the first object stops moving, how can I merge the sounds of two objects instead of playing them seperately?

Most of this will be achieved using the java.sound.sampled library. Focus on Clip 's functionality. This site provides some really good boilerplate using both samples and MIDI files. It even has an example for gaming.

Anyway, based off of StackOverflow's javasound page , here is a crude example of playing two Clip s at once:

public static void main(String... args) throws Exception {
    URL url1 = new URL("http://www.websitewithsomewav/noise1.wav");
    Clip clip1 = AudioSystem.getClip();
    AudioInputStream stream1 = AudioSystem.getAudioInputStream(url1);
    clip1.open(stream1);

    URL url2 = new URL("http://www.websitewithsomewav/noise2.wav");
    Clip clip2 = AudioSystem.getClip();
    AudioInputStream stream2 = AudioSystem.getAudioInputStream(url2);
    clip2.open(ais2);

    clip1.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!");
        }
    });
}

Update

If you absolutely must use a single input stream, you can try MixingAudioInputStream

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM