sound not playing in jar

别来无恙 提交于 2019-11-29 18:04:51

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

then

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

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!