play .wav file from jar as resource using java

前端 未结 9 577
离开以前
离开以前 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:08

    Perfect Solution.......

    URL url = this.getClass().getResource("sounds/beep.au");
    
    String urls=url.toString(); 
    urls=urls.replaceFirst("file:/", "file:///");
    
    AudioClip ac=Applet.newAudioClip(new URL(urls));
    
    ac.play();
    
    0 讨论(0)
  • 2020-11-30 11:10
         try {
            AudioPlayer.player.start(new AudioStream(getClass().getResourceAsStream("/sound/SystemNotification.wav")));
        } catch (Exception e) {
            e.printStackTrace();
        }
    
    0 讨论(0)
  • 2020-11-30 11:11

    Use Class.getResourceAsStream()

    Once you have a handle to the inputStream, get the audioInputStream and do the rest.

    InputStream is = getClass().getResourceAsStream("......");
    AudioInputStream ais = AudioSystem.getAudioInputStream(is);
    Clip clip = AudioSystem.getClip();
    clip.open(ais);
    
    0 讨论(0)
  • 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();
    }
    }
    
    0 讨论(0)
  • 2020-11-30 11:17

    Please refer to my previous answer at making a single-jar java application . The title is misleading, but the poster was trying to do something almost identical to you. Some of the best details are in the link to the chat log.

    0 讨论(0)
  • 2020-11-30 11:22

    Have you tried:

    InputStream is= getClass().getResourceAsStream("/images/ads/WindowsNavigationStart.wav");
    AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(is);
    

    Essentially I do not think you can create a File out of a URI in the jar file. But you can pass the input stream directly.

    0 讨论(0)
提交回复
热议问题