我一直尝试在Java中一次播放多个声音,我一次播放1个声音没问题,但是如果我一次尝试播放3个声音,那么只播放1个声音(我希望这是有意义的)
这是我的代码:
public static void play(String file) {
try {
clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(new File(file)));
clip.start();
while (!clip.isRunning())
Thread.sleep(10);
while (clip.isRunning())
Thread.sleep(10);
clip.close();
} catch (Exception e) {
e.printStackTrace();
}
}
我如何使用此方法的示例:
AudioPlayer.play("sound1.wav");
当我也希望能够这样做时
AudioPlayer.play("sound1.wav");
AudioPlayer.play("sound2.wav");
AudioPlayer.play("sound3.wav");
此外,不重要但也做这样的事情也很好:
AudioPlayer.getPlayingSound("sound1.wav").setVolume(-0.85f);
答案 0 :(得分:1)
要播放剪辑,您应该遵循java文档中的以下代码:
import java.net.URL;
import javax.swing.*;
import javax.sound.sampled.*;
public class LoopSound {
public static void main(String[] args) throws Exception {
URL url = new URL(
"http://pscode.org/media/leftright.wav");
Clip clip = AudioSystem.getClip();
// getAudioInputStream() also accepts a File or InputStream
AudioInputStream ais = AudioSystem.
getAudioInputStream( url );
clip.open(ais);
clip.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!");
}
});
}}
由于你想同时播放剪辑,你可以尝试这样做:
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!");
}
});
}
}
答案 1 :(得分:1)
您可能会尝试使用多线程同时播放多个声音。