无法在jar文件中播放嵌入的声音 [英] Cannot play embedded sound in a jar file

查看:180
本文介绍了无法在jar文件中播放嵌入的声音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个名为BatteryBeeper的个人使用软件。当我设定要提醒的费用时,它将提醒我为笔记本电脑充电。

I am creating a software for personal use titled BatteryBeeper. It will remind me to charge the laptop when the charge is whatever I set to be reminded at.

应该在充电达到设定的阈值时播放声音。

It is supposed to play a sound when the charge hits the set threshold.

我看看答案:声音不在罐中播放,而我的 AudioInputStream 的构造类似于Jigar Joshi提到的构造。

I had a look at the answer: sound not playing in jar and my AudioInputStream is constructed similar to what Jigar Joshi mentioned.

但是我得到一个空异常:

However I get a null exception:

java.lang.NullPointerException
    at com.sun.media.sound.SoftMidiAudioFileReader.getAudioInputStream(Unknown Source)
    at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
    at demo.BatteryBeeper.setupSoundPlayback(BatteryBeeper.java:169)
    at demo.BatteryBeeper.<init>(BatteryBeeper.java:41)
    at demo.BatteryBeeper.main(BatteryBeeper.java:35)  

这是我加载声音的代码:

Here is my code to load the sound:

public void setupSoundPlayback(){
        try{
            buzzer = AudioSystem.getClip();
            in = AudioSystem.getAudioInputStream(BatteryBeeper.class.
                    getResourceAsStream("sound/buzzer3_x.wav"));
            buzzer.open(in);
        }catch(Exception e){
            e.printStackTrace();
        }

    }  

以下是播放代码:

public void playSound(){
        buzzer.start();
    }  

是什么原因引起的?

这是一个常见的Eclipse项目。在 src 下有一个 sound 文件夹,其中包含wave文件

This is a usual Eclipse project. There is a sound folder under src which has the wave file

在AlexR回答之后,我更改了路径并得到了一个新的例外:

After AlexR's answer, I changed the path and got a new exception:

javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input stream
    at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
    at demo.BatteryBeeper.setupSoundPlayback(BatteryBeeper.java:169)
    at demo.BatteryBeeper.<init>(BatteryBeeper.java:41)
    at demo.BatteryBeeper.main(BatteryBeeper.java:35)


推荐答案

您的问题不在于播放声音。您的问题在于对嵌入式资源的访问。当您使用 BatteryBeeper.class.getResourceAsStream( sound / buzzer3_x.wav)时,您尝试检索位于类 BatteryBeeper 是。这意味着您的文件位于 /demo/sound/buzzer3_x.wav 中。看来这是错误的。如果您的文件确实位于 sound / buzzer3_x.wav 中,请使用 getResourceAsStream( / sound / buzzer3_x.wav)(请注意路径中的前斜线)。

You problem is not in playing the sound. Your problem is in access to embedded resource. When you are using BatteryBeeper.class.getResourceAsStream("sound/buzzer3_x.wav") you try to retrieve resource located in same package where class BatteryBeeper is. This means that your file is in /demo/sound/buzzer3_x.wav. It seems this is wrong. If your file really is in sound/buzzer3_x.wav use getResourceAsStream("/sound/buzzer3_x.wav") (pay attention on the leading slash in the path).

这篇关于无法在jar文件中播放嵌入的声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆