音乐不会';t在应用程序中播放(javax.sound.sampled.Clip)
我的问题是:为什么在这个应用程序中不播放音乐?(IDE是Eclipse)问题在于,您的主应用程序线程在声音片段播放之前退出。您可以在音乐不会';t在应用程序中播放(javax.sound.sampled.Clip),java,javasound,Java,Javasound,我的问题是:为什么在这个应用程序中不播放音乐?(IDE是Eclipse)问题在于,您的主应用程序线程在声音片段播放之前退出。您可以在clip.start()之后调用Thread.sleep,但最好创建一个专用线程来跟踪播放时的音频数据: import javax.sound.sampled.*; import java.io.File; public class PlayAudio{ public static void main(String args[])throws Exception{
clip.start()
之后调用Thread.sleep
,但最好创建一个专用线程来跟踪播放时的音频数据:
import javax.sound.sampled.*;
import java.io.File;
public class PlayAudio{
public static void main(String args[])throws Exception{
File wavFile = new File("C:\\Users\\User\\Desktop\\Wate.wav");
AudioInputStream ais = AudioSystem.getAudioInputStream(wavFile);
Clip clip=AudioSystem.getClip();
clip.open(ais);
clip.start();
}
}
1) 路径名正确吗?2) 有扬声器吗?3) 扬声器开着吗?4) 检查音量。我感觉程序在播放开始前退出。尝试在clip.start()
之后添加Thread.sleep(10000)
,可能会有帮助。我认为没有任何错误。剪辑的持续时间是0.001秒吗?@Chia'sJaJa别忘了这样做。如果您觉得以前的问题有用,您也可以重温这些问题并接受答案。通过显示JOptionPane
来延长main(String[])
的“quick-n-dirty”方法可以在上看到+谢谢你的方法。
public class PlayAudio {
AudioFormat audioFormat;
AudioInputStream audioInputStream;
SourceDataLine sourceDataLine;
boolean stopPlayback = false;
public void playAudio(File soundFile) throws UnsupportedAudioFileException,
IOException, LineUnavailableException {
audioInputStream = AudioSystem.getAudioInputStream(soundFile);
audioFormat = audioInputStream.getFormat();
DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, audioFormat);
sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
new Thread(new PlayThread()).start();
}
public static void main(String[] args) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
new PlayAudio().playAudio(new File("myclip.wav"));
}
class PlayThread implements Runnable {
byte soundBuffer[] = new byte[10000];
@Override
public void run() {
try {
sourceDataLine.open(audioFormat);
sourceDataLine.start();
int cnt;
while ((cnt = audioInputStream.read(soundBuffer, 0,
soundBuffer.length)) != -1 && stopPlayback == false) {
if (cnt > 1) {
sourceDataLine.write(soundBuffer, 0, cnt);
}
}
sourceDataLine.drain();
sourceDataLine.close();
stopPlayback = false;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}