play .wav file from jar as resource using java

前端 未结 9 588
离开以前
离开以前 2020-11-30 10:56

I want to play a .wav file using java code which is in a jar file as resource. My code is look like this -

try {
     URL defaultSound = getClass().getResou         


        
9条回答
  •  悲&欢浪女
    2020-11-30 11:14

    The following allows me to play a sound in Eclipse project and an exported jar file:
    - note the BufferedInputStream is used
    - Note, inputStream is used instead of file.

    In my main():

    playAlarmSound();
    

    in my class:

    public static void playAlarmSound() {
    ClassLoader classLoader = App.class.getClassLoader();
    InputStream inputStream = classLoader.getResourceAsStream("alarmsound.wav");
    try {
      Clip clip = AudioSystem.getClip();
      AudioInputStream ais = AudioSystem.getAudioInputStream(new BufferedInputStream(inputStream));
      clip.open(ais);
      clip.start();
    } catch (IOException | LineUnavailableException | UnsupportedAudioFileException e) {
      System.err.println("ERROR: Playing sound has failed");
      e.printStackTrace();
    }
    }
    

提交回复
热议问题