sound will play in eclipse but not in exported jar file

前端 未结 2 384
没有蜡笔的小新
没有蜡笔的小新 2021-01-15 05:14

Sound does not play when I run the JAR, but it does when I run it in eclipse.

Here is where I load the clips: (the files are loaded from the directory of the jar, No

相关标签:
2条回答
  • 2021-01-15 05:54

    I struggled with this as well. You need to use

    getClass().getSystemResource("pathToResourceFromClass")

    For example, if your project structure is like the following:

    -ProjectName

    -----src

    ----------SomeClass.java

    -----images

    ----------SomeImage.png

    Then from SomeClass.java, you would use

    getClass().getSystemResource("images/SomeImage.png")
    

    to obtain the URL object which references that file. You could then pass that URL object to the constructor of ImageIcon if you want.

    Note that getClass().getResource() does not work for images or sound files in a jar file!!! I've spent many hours on this, and getResource() does not work. You have to use getSystemResource(..) for resources within a jar file.

    Let me know if you have any questions about this. I'd be glad to clarify any confusing points.

    0 讨论(0)
  • 2021-01-15 05:57

    The reason your sound is not playing because it is most likely not being compiled into your runnable jar and thus cannot be found. The best way to have it compile into a runnable jar is to create a source folder in eclipse, and then add your sound file in there. It will then be compiled into your jar

    0 讨论(0)
提交回复
热议问题