在 Java 中播放 wav 的问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/577724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trouble playing wav in Java
提问by yanchenko
I'm trying to play a
我正在尝试玩
PCM_UNSIGNED 11025.0 Hz, 8 bit, mono, 1 bytes/frame
file as described here (1)and here(2).
The first approach works, but I don't want to depend on sun.*stuff. The second results in just some leading frames being played, that sounds more like a click. Can't be an IO issue as I'm playing from a ByteArrayInputStream.
第一种方法有效,但我不想依赖sun.*东西。第二个结果只播放一些前导帧,这听起来更像是点击。不可能是 IO 问题,因为我是从 ByteArrayInputStream 播放的。
Plz share your ideas on why might this happen. TIA.
请分享您对为什么会发生这种情况的想法。TIA。
回答by McDowell
I'm not sure why the second approach you linked to starts another thread; I believe the audio will be played in its own thread anyway. Is the problem that your application finishes before the clip has finished playing?
我不确定为什么您链接的第二种方法会启动另一个线程;我相信无论如何音频都会在它自己的线程中播放。问题是您的应用程序在剪辑播放完毕之前完成了吗?
import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.LineEvent.Type;
private static void playClip(File clipFile) throws IOException,
UnsupportedAudioFileException, LineUnavailableException, InterruptedException {
class AudioListener implements LineListener {
private boolean done = false;
@Override public synchronized void update(LineEvent event) {
Type eventType = event.getType();
if (eventType == Type.STOP || eventType == Type.CLOSE) {
done = true;
notifyAll();
}
}
public synchronized void waitUntilDone() throws InterruptedException {
while (!done) { wait(); }
}
}
AudioListener listener = new AudioListener();
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(clipFile);
try {
Clip clip = AudioSystem.getClip();
clip.addLineListener(listener);
clip.open(audioInputStream);
try {
clip.start();
listener.waitUntilDone();
} finally {
clip.close();
}
} finally {
audioInputStream.close();
}
}

