Playing AudioClip with .wav in another JAVA package

0

I use this code to play sounds in my application, but it only plays audio if it is in the project folder, not inside a package. And if I export my project by creating a .jar it does not include the media files. I've tried changing the path by adding the package, in this case sounds, but it does not play "/sons/audio.wav". Thanks.

try {
    AudioClip c = Applet.newAudioClip(new File("audio.wav").toURL());
    c.play();
} catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
    
asked by anonymous 01.03.2017 / 21:30

2 answers

0

If it is in the resource folder you can use getResourceAsStream :

...
AudioClip c = Applet.newAudioClip(Principal.class.getResource("/recurso/audio.wav").toURI().toURL());
c.play();
...

    
01.03.2017 / 21:36
1

If you have a directory from the project root, the correct path is:

"sons/audio.wav"

Note that it is missing the slash. I recommend doing tests with the class File , creating a file and taking the complete path or verifying if it exists:

File f = new File("sons/audio.wav");
System.out.println(f.getAbsolutePath());
System.out.println(f.exists())
    
01.03.2017 / 21:37