gpt4 book ai didi

java - 一次播放多个声音 Java

转载 作者:行者123 更新时间:2023-11-30 08:32:25 25 4
gpt4 key购买 nike

我一直在尝试在 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);

最佳答案

要播放剪辑,您应该遵循 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!");
}
});
}
}

关于java - 一次播放多个声音 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40153779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com