开发者

sound not playing in jar

I have packed all the class files and resources 开发者_如何学编程as a jar but on execution the sound files wont play. My package structure is:

+project
|_classes
|_ _*.class
|_resources
|_ _ *.jpg,*.wav

Code:

AudioInputStream inputStream = AudioSystem.getAudioInputStream(kidsClassRoom.class.getResourceAsStream("../resources/"+file));

getting a null when this line is executed!!


An alternate theory to those already presented. Often successful getResource() calls depend on the class loader instance that is called to locate them. For this reason, I would recommend to use an instance of a user defined object, from which to call getResource(). E.G.

// Sanity check
System.out.println("The value of 'file' is: " + file);
// Presuming kidsClassRoom1 is an instance of kidsClassRoom
AudioInputStream inputStream = AudioSystem.
    getAudioInputStream(
        kidsClassRoom1.
            getClass().
            getResourceAsStream("/resources/"+file));

You might also note that snippet uses the prefix of "/" for the resource. Contrary to what others are saying, I am confident that means 'from the root' of the resource path, in whatever Jar on the run-time class-path it is found. Leaving the '/' or '../' out will have the class loader searching for the resource in a sub-path of the class that this is occurring in.

Of course - make sure the Wav ends up in the Jar! Copy/rename the .jar to a .zip and double click it is the 'quick & dirty' way to examine the archive contents on Windows.


Create a package named resources as shown below

sound not playing in jar

then

 AudioSystem.getAudioInputStream(kidsClassRoom.class.getResourceAsStream("resources/"+file));


This is my function for playing a looping sound file in jars, it works fine for me.

It appears that getResourceAsStream() doesn't work with jars. however, getResource() does.

public synchronized void alarm() {
    try {
        crit = AudioSystem.getClip();
        AudioInputStream inputStream1 = AudioSystem.getAudioInputStream(this.getClass().getResource("critical.wav"));
        crit.open(inputStream1);
        crit.loop(Clip.LOOP_CONTINUOUSLY);

    } catch (Exception e) {
        System.err.println(e.getMessage());
        }
}


When you do getResourceAsStream, it is not relative to the current class, but the root of the archive. That is, first try to remove ../.


The important thing to note is that in the exported jar the resources are not stored as files (Read this somewhere, someone more knowledgeable please input). So it's best to get the resource as a URL Object first then pass that to the AudioInputStream Object.

URL url = YourClass.class.getResource(filename);
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(url);

If the resource is in a subfolder, remember to add it to your filename path.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜