简体   繁体   English

.wav声音无法在Java中播放

[英].wav sounds not playing in Java

I am currently using this function to play .WAV files 我目前正在使用此功能播放.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();
      }
}

The problem is that no sound is being played when I call the function on a file, no errors or exceptions are thrown or whatsoever the program just starts and stops, no sound plays, I tried with a lot of different .WAV files with no success. 问题是,当我在文件上调用函数时,没有声音在播放,没有错误或异常抛出,或者程序只是启动和停止,没有声音在播放,我尝试了很多不同的.WAV文件,但均未成功。

The programm stops before it has time to play the sound since start is non-blocking. 由于开始是非阻塞的,因此程序在有时间播放声音之前停止。

Try the following : 尝试以下方法:

clip.start();
clip.drain();
clip.close();

This works for me: 这对我有用:

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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM