我正试图在Java中播放基本声音......
这是我的代码,基于各种论坛上的代码:
Clip clip = null;
try {
clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File(url));
clip.open(inputStream);
} catch (LineUnavailableException | IOException | UnsupportedAudioFileException ex) {
Logger.getLogger(Pomodoro.class.getName()).log(Level.SEVERE, null, ex);
}
return clip;
我检查过:new File(url).exists();
返回true,我检查文件类型是否真的是音频WAV(audio / x-wav),我检查了问题是否仍存在于另一个文件中......我不明白我做错了什么。
错误:
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.IllegalArgumentException: Invalid format
at org.classpath.icedtea.pulseaudio.PulseAudioDataLine.createStream(PulseAudioDataLine.java:142)
at org.classpath.icedtea.pulseaudio.PulseAudioDataLine.open(PulseAudioDataLine.java:99)
at org.classpath.icedtea.pulseaudio.PulseAudioDataLine.open(PulseAudioDataLine.java:283)
at org.classpath.icedtea.pulseaudio.PulseAudioClip.open(PulseAudioClip.java:402)
at org.classpath.icedtea.pulseaudio.PulseAudioClip.open(PulseAudioClip.java:453)
帮助!
答案 0 :(得分:3)
我终于找到了我的问题的副本。对不起我打扰了你。
AudioInputStream is not working
我的代码变成了:
Clip clip = null;
try {
AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File(url));
DataLine.Info info = new DataLine.Info(Clip.class, inputStream.getFormat());
clip = (Clip)AudioSystem.getLine(info);
clip.open(inputStream);
} catch (LineUnavailableException | IOException | UnsupportedAudioFileException ex) {
Logger.getLogger(Pomodoro.class.getName()).log(Level.SEVERE, null, ex);
}
return clip;
然而,我很惊讶我以前的代码没有用。有时,我非常渴望Java ......
答案 1 :(得分:0)
您可以使用以下代码在Java中播放声音。
try {
DataLine.Info daInfo = new DataLine.Info(Clip.class, null);
try {
URL sounURL = ClassName.class.getResource("/com/notification.wav");
AudioInputStream inputStream = AudioSystem.getAudioInputStream(sounURL);
DataLine.Info info = new DataLine.Info(Clip.class, inputStream.getFormat());
Clip clip = (Clip) AudioSystem.getLine(info);
clip.open(inputStream);
clip.start();
} catch (LineUnavailableException e) {
e.printStackTrace();
} catch (UnsupportedAudioFileException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
} catch (Exception e) {
System.out.println("music");
}