简体   繁体   中英

play .wav file from jar as resource using java

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().getResource("/images/ads/WindowsNavigationStart.wav");
     // getClass().getSy.getResource("/images/ads/WindowsNavigationStart.wav");
     File soundFile = new File(defaultSound.toURI());
     AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(soundFile);
     Clip clip = AudioSystem.getClip();
     clip.open(audioInputStream);
     clip.start( );
} catch (Exception ex) {
     ex.printStackTrace();
}

The file WindowsNavigationStart.wav is exist in one of my jar file. But getting the following exception -

java.lang.IllegalArgumentException: URI is not hierarchical
at java.io.File.<init>(File.java:363)
at au.com.webscan.wwwizard.app.admin.customfile.UpOneLevelFolder.btnUpFolderActionPerformed(Unknown Source)
at au.com.webscan.wwwizard.app.admin.customfile.UpOneLevelFolder.access$000(Unknown Source)
at au.com.webscan.wwwizard.app.admin.customfile.UpOneLevelFolder$1.actionPerformed(Unknown Source)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:272)
at java.awt.Component.processMouseEvent(Component.java:6288)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6053)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4651)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4481)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4481)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:643)
at java.awt.EventQueue.access$000(EventQueue.java:84)
at java.awt.EventQueue$1.run(EventQueue.java:602)
at java.awt.EventQueue$1.run(EventQueue.java:600)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
at java.awt.EventQueue$2.run(EventQueue.java:616)
at java.awt.EventQueue$2.run(EventQueue.java:614)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:613)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

Please give me a solution. Thank you all.

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.

Change:

AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(soundFile);

To:

System.out.println("defaultSound " + defaultSound);  // check the URL!
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(defaultSound);

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

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

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.

     try {
        AudioPlayer.player.start(new AudioStream(getClass().getResourceAsStream("/sound/SystemNotification.wav")));
    } catch (Exception e) {
        e.printStackTrace();
    }

this worked fine for me:

public void playSound() {
        InputStream in;
        try {
            in = new BufferedInputStream(new FileInputStream(new File(
                    getClass().getClassLoader()
                            .getResource("com/kaito/resources/sound.wav").getPath())));
            AudioStream audioStream = new AudioStream(in);
            AudioPlayer.player.start(audioStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

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

like Kal wrote :

  1. InputStream is = getClass().getResourceAsStream("......");
  2. AudioInputStream ais = AudioSystem.getAudioInputStream(is);...

I did just that and it didn't work at first but the problem of "java.io.IOException" was that I used File.separator and for some reason win 8.1 couldn't handle "\\\\"...

public AudioInputStream getSound(String fileName){
    InputStream inputSound;
    AudioInputStream audioInStr;
    String fs = File.separator;

    try {
       absolutePath = fs +packageName+ fs +folderName+ fs +fileName;
       inputSound = getClass().getResourceAsStream(absolutePath);

       //if null pointer exception try unix, for some reason \\ doesn't work on win 8.1
       if(inputSound == null) {
           absolutePath = "/" + packageName + "/" + folderName + "/" + fileName;
           inputSound = getClass().getResourceAsStream(absolutePath);
       }

       audioInStr = AudioSystem.getAudioInputStream(new BufferedInputStream(inputSound));
       return audioInStr;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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