音频无法播放JAR文件

时间:2015-01-12 20:14:14

标签: java audio jar resources

我创建了一个在netbeans IDE中播放音频的项目。这些音频文件放在Classes文件夹中。 虽然当我将其创建为JAR文件时,却无法找到音频文件。我甚至将文件复制并粘贴到新的dist文件夹中。 这是一段代码:

    private void playSound39() 
{
  try
  {
/**Sound player code from:
http://alvinalexander.com/java/java-audio-example-java-au-play-sound    
*/      
    // the input stream portion of this recipe comes from a javaworld.com article.
    InputStream inputStream = getClass().getResourceAsStream("./beep39.wav");
    AudioStream audioStream = new AudioStream(inputStream);
    AudioPlayer.player.start(audioStream);
  }
  catch (Exception e)
  {
    JOptionPane.showMessageDialog(null,"Audio file not found!");
  }   
}

3 个答案:

答案 0 :(得分:3)

如果要将音频文件嵌入程序中,必须将其放在包中的src文件夹中。
例如,我将演示一个代码,用于将图标设置为按钮(也适用于音频文件):
在创建我写的JFrame时:

jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Icon/PatientBig.png")));

我的项目中有一个名为GUI的软件包,其中包含一个名为Icons的子包,其中存在我的图标,它们都位于src文件夹中。
当您使用getClass().getResource函数时,我更喜欢使用绝对路径 看到你的回复后,我注意到你在类路径的开头继续使用.,我复制了你发布的代码片段并从路径的开头删除了.并放置了我的音频文件{ {1}}在默认包中的bark.wav文件夹中,它可以正常工作

src

然后我将音频文件放在一个名为public class test { private void playSound39() { try { /** * Sound player code from: * http://alvinalexander.com/java/java-audio-example-java-au-play-sound */ // the input stream portion of this recipe comes from a javaworld.com article. InputStream inputStream = getClass().getResourceAsStream("/bark.wav"); AudioStream audioStream = new AudioStream(inputStream); AudioPlayer.player.start(audioStream); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Audio file not found!"); } } public static void main(String[] args){ new test().playSound39(); } } 的包中,并修改了test1函数中的路径,并再次起作用:

getResourceAsStream

最重要的是从路径中移除public class test { private void playSound39() { try { /** * Sound player code from: * http://alvinalexander.com/java/java-audio-example-java-au-play-sound */ // the input stream portion of this recipe comes from a javaworld.com article. InputStream inputStream = getClass().getResourceAsStream("/test1/bark.wav"); AudioStream audioStream = new AudioStream(inputStream); AudioPlayer.player.start(audioStream); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Audio file not found!"); } } public static void main(String[] args){ new test().playSound39(); } }

答案 1 :(得分:0)

试试这个

InputStream in = getClass().getResourceAsStream("/beep39.wav"); 

答案 2 :(得分:0)

我认为你需要绕过InputStream的使用。运行getAudioInputStream方法时,使用InputStream作为参数会触发音频文件的可标记性和可重置性测试。音频文件通常不通过这些测试。如果使用URL或File参数创建AudioInputStream,则会绕过这些测试。我更喜欢URL,因为它似乎更健壮,可以"看到"广口瓶中。

URL url = getClass().getResource("./beep39.wav");
AudioInputStream ais = AudioSystem.getAudioInputStream(url);

然后,在while循环中,您将在AudioInputStream上执行read方法并将数据发送到SourceDataLine。

Java教程在audio trail中介绍了这一点。这个链接跳到了教程的中间。

AFAIK,没有" AudioPlayer"在Java 7 SDK中。

相关问题