gpt4 book ai didi

java - 剪辑无法在Java中播放声音

转载 作者:行者123 更新时间:2023-12-03 02:11:45 24 4
gpt4 key购买 nike

以下代码既不会发出声音,也不会打印堆栈跟踪。如果我进行调试,则跳过clip.start()将使声音播放一秒钟。有人知道我在做什么错吗?谢谢。

import java.net.URL;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;

public class Driver {

public static void main(String[] args) {
try {
URL url = new URL("http://api.voicerss.org/?KEY=b1a362bc35014e9c9dcd8d3536aac7ad&SRC=This%20is%20a%20test&HL=en-gb&C=WAV&F=48khz_16bit_stereo");
AudioInputStream sound = AudioSystem.getAudioInputStream(url);
DataLine.Info info = new DataLine.Info (Clip.class, sound.getFormat());
Clip clip = (Clip) AudioSystem.getLine(info);
clip.open(sound);
clip.start();
while(clip.isRunning());
} catch (Exception e) {
e.printStackTrace();
}
}

}

同样,将 while(clip.isRunning(());更改为 while(clip.isRunning()) System.out.println("running");不会导致任何输出。

最佳答案

这是关于线程的问题。
当我尝试在事件调度线程中运行它时,它运行正常。
您可以从以下讨论中了解EDT:

Why do I need Swing Utilities and how do I use it?



注意:我希望其他人可以为此找到更好的解决方案。
import java.io.IOException;
import java.net.URL;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.SwingUtilities;

public class Driver {

@SuppressWarnings("empty-statement")
public static void main(String[] args) {
try {
URL url = new URL("http://api.voicerss.org/?KEY=b1a362bc35014e9c9dcd8d3536aac7ad&SRC=Your%20a%20fag&HL=en-gb&C=WAV&F=48khz_16bit_stereo");
AudioInputStream sound = AudioSystem.getAudioInputStream(url);
DataLine.Info info = new DataLine.Info (Clip.class, sound.getFormat());
final Clip clip = (Clip)AudioSystem.getLine(info);
clip.open(sound);
clip.setFramePosition(0);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
clip.start();
}
});

} catch (IOException | LineUnavailableException | UnsupportedAudioFileException e) {
e.printStackTrace();
}
}

}

关于java - 剪辑无法在Java中播放声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23378157/

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