Java 中没有播放 .wav 声音
.wav sounds not playing in Java
我目前正在使用此功能播放.WAV文件
public void playSound(String sound){
try {
// Open an audio input stream.
URL url = this.getClass().getClassLoader().getResource(sound);
AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
// Get a sound clip resource.
Clip clip = AudioSystem.getClip();
// Open audio clip and load samples from the audio input stream.
clip.open(audioIn);
clip.start();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
问题是当我在文件上调用该函数时没有播放声音,没有抛出任何错误或异常,或者程序只是启动和停止,没有播放声音,我尝试了很多不同的 . WAV 文件没有成功。
由于 start 是非阻塞的,因此程序在有时间播放声音之前就停止了。
尝试以下操作:
clip.start();
clip.drain();
clip.close();
这对我有用:
public void sound() {
try{
AudioInputStream ais = AudioSystem.getAudioInputStream(new File("./sounds/player-laser.wav"));
Clip test = AudioSystem.getClip();
test.open(ais);
test.loop(0);
}catch(Exception ex){
ex.printStackTrace();
}
}
我目前正在使用此功能播放.WAV文件
public void playSound(String sound){
try {
// Open an audio input stream.
URL url = this.getClass().getClassLoader().getResource(sound);
AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
// Get a sound clip resource.
Clip clip = AudioSystem.getClip();
// Open audio clip and load samples from the audio input stream.
clip.open(audioIn);
clip.start();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
问题是当我在文件上调用该函数时没有播放声音,没有抛出任何错误或异常,或者程序只是启动和停止,没有播放声音,我尝试了很多不同的 . WAV 文件没有成功。
由于 start 是非阻塞的,因此程序在有时间播放声音之前就停止了。
尝试以下操作:
clip.start();
clip.drain();
clip.close();
这对我有用:
public void sound() {
try{
AudioInputStream ais = AudioSystem.getAudioInputStream(new File("./sounds/player-laser.wav"));
Clip test = AudioSystem.getClip();
test.open(ais);
test.loop(0);
}catch(Exception ex){
ex.printStackTrace();
}
}