简体   繁体   English

我如何一起播放两种声音?

[英]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. 好吧,我正在用Java编写一个游戏项目,我想实现这样的东西:当一个对象开始移动时,它会产生一些声音效果,而当另一个对象在第一个对象停止之前开始移动时,它也会产生一些声音。效果。 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. 其中大部分将使用java.sound.sampled库实现。 Focus on Clip 's functionality. 专注于Clip的功能。 This site provides some really good boilerplate using both samples and MIDI files. 该站点使用样本和MIDI文件提供了一些非常好的样板。 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: 无论如何,基于StackOverflow的javasound页面 ,这是一次播放两个Clip的简单示例:

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 如果绝对必须使用单个输入流,则可以尝试MixingAudioInputStream

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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