javax.sound.sampled 它是如何工作的?
我正在尝试用 Java 播放声音。 到目前为止一切进展顺利,谢谢,但我在理解它是如何工作时遇到问题。
我编写了一个执行播放的函数:
private static void PlaySound(String path) {
try {
final File SoundFile = new File(path);
AudioInputStream Sound = AudioSystem.getAudioInputStream(SoundFile);
DataLine.Info info = new DataLine.Info(Clip.class, Sound.getFormat());
Clip clip = (Clip) AudioSystem.getLine(info);
clip.open(Sound);
clip.addLineListener(new LineListener() {
public void update (LineEvent event) {
if (event.getType() == LineEvent.Type.STOP) {
event.getLine().close();
System.out.printf("Playback ended!");
System.exit(0);
}
}
});
System.out.printf("This sound is %f seconds long.", (clip.getMicrosecondLength() / 1000.0d));
clip.start();
} catch (Exception e) {
ErrorHandler(e);
}
}
现在这个函数几乎可以正常工作:当声音结束时,它会调用 event.getLine().close();函数,但它陷入了“无限循环”(不确定是否是),并且在执行该语句之后没有任何内容,并且程序一直运行,直到我手动终止它。
如果我将行更改
if (event.getType() == LineEvent.Type.STOP) {
为,
if (event.getType() == LineEvent.Type.CLOSE) {
则播放声音,并且程序正确退出,但在 event.getLine().close(); 之后仍然没有任何语句。被处决。
问题是:这是 event.getLine().close() 的预期行为,还是我做错了什么?
解决方案:
LineListener 实际上是基于一个过时的事实,即 Java Sound 存在 bug,我们需要显式退出 vm。如果没有监听器,代码就可以正常工作。
I am trying to play a sound in Java.
So far it is going well, thank you, but I have a problem understanding how does this work.
I wrote a function that does the playback:
private static void PlaySound(String path) {
try {
final File SoundFile = new File(path);
AudioInputStream Sound = AudioSystem.getAudioInputStream(SoundFile);
DataLine.Info info = new DataLine.Info(Clip.class, Sound.getFormat());
Clip clip = (Clip) AudioSystem.getLine(info);
clip.open(Sound);
clip.addLineListener(new LineListener() {
public void update (LineEvent event) {
if (event.getType() == LineEvent.Type.STOP) {
event.getLine().close();
System.out.printf("Playback ended!");
System.exit(0);
}
}
});
System.out.printf("This sound is %f seconds long.", (clip.getMicrosecondLength() / 1000.0d));
clip.start();
} catch (Exception e) {
ErrorHandler(e);
}
}
Now this function works almost fine: when the sound has ended, it calls the event.getLine().close(); function, but it is stuck in an "infinite loop" (not sure if it is) and nothing after that statement gets executed, and the program runs until I kill it manually.
If I change the line
if (event.getType() == LineEvent.Type.STOP) {
to
if (event.getType() == LineEvent.Type.CLOSE) {
then the sound plays, and the program exits correctly, but still none of the statement after the event.getLine().close(); are executed.
The question is: is this the intended behavior of event.getLine().close(), or I am doing something wrong?
Solution:
The LineListener is actually based on an outdated fact, that Java Sound has a bug in it, and we need to exit explicitly from the vm. Without the listener, the code just works fine.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
查看是否引发异常:
See if it's raising an exception: