使用java从jar作为资源播放.wav文件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用java从jar作为资源播放.wav文件相关的知识,希望对你有一定的参考价值。

我想使用java代码播放.wav文件,该代码位于jar文件中作为资源。我的代码看起来像这样 -

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

WindowsNavigationStart.wav文件存在于我的一个jar文件中。但得到以下例外 -

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)

请给我一个解决方案。谢谢你们。

答案

更改:

AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(soundFile);

至:

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

你有没有尝试过:

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

基本上我认为你不能在jar文件中用URI创建一个文件。但是您可以直接传递输入流。

另一答案

使用Class.getResourceAsStream()

获得inputStream的句柄后,获取audioInputStream并完成剩下的工作。

InputStream is = getClass().getResourceAsStream("......");
AudioInputStream ais = AudioSystem.getAudioInputStream(is);
Clip clip = AudioSystem.getClip();
clip.open(ais);
另一答案

完美解决方案.......

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();
另一答案

请参阅我之前在making a single-jar java application的回答。标题是误导性的,但海报试图做一些几乎与你相同的事情。一些最佳细节位于聊天记录的链接中。

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

这对我来说很好:

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();
        }
    }
另一答案

以下允许我在Eclipse项目和导出的jar文件中播放声音: - 注意使用BufferedInputStream - 注意,使用inputStream而不是file。

在我的main()中:

playAlarmSound();

在我班上:

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();
}
}
另一答案

像Kal写道:

  1. InputStream = getClass()。getResourceAsStream(“......”);
  2. AudioInputStream ais = AudioSystem.getAudioInputStream(also);

我这样做了,它起初没有用,但是“java.io.IOException”的问题是我使用了File.separator,由于某种原因,win 8.1无法处理“\”......

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

以上是关于使用java从jar作为资源播放.wav文件的主要内容,如果未能解决你的问题,请参考以下文章

如何播放wav文件

在从 Intellij IDEA 创建的 jar 文件中播放 .wav 时出现问题

如何使用 java 播放 .wav 文件

Java中可靠的声音API,用于简单的数字样本播放

VB.NET如何调用并播放项目资源内的WAV文件。

从计算机的文件中播放 Java 中的 .wav 文件