Play Audioclip with . wav in another JAVA package

Asked

Viewed 283 times

0

I use this code to play sounds in my application, but it only plays the audio if it is in the project folder, and not within a package. And if I export my project by creating a . jar it does not include the media files. I have tried to change the path by adding the package, in this case sounds, but it does not play "/sounds/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();
}
  • I think the problem is the package hierarchy. If possible, post an image of how it is. Using File, java will always look for the file in the OS file system.

2 answers

1

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

"sons/audio.wav"

Note that you are without the bar. I recommend doing tests with the class File, creating a file and taking the full path or checking if it exists:

File f = new File("sons/audio.wav");
System.out.println(f.getAbsolutePath());
System.out.println(f.exists())
  • I tested, and did not execute.

0


If you are in the resource folder you can use the getResourceAsStream:

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

Estrutura

  • Audioclip a = Applet.newAudioClip(Controleatendimento.class.getResourceAsStream("/resource/audio.wav"). toURI(). toString());

  • Make a mistake, ask to cast a cast, but then get wrong.

  • @Jessésantos does not have the toString() see now how it looks

  • Did not, still asks to be made a cast, type File, when I make the error.

  • You’re using the class Applet of what package?

  • import java.applet.Applet; import java.applet.Audioclip;

  • @Did you use exactly the code I passed there? I’m not using any class File how are you reporting.

  • @diegofm added the structure

  • @Sorack the comment went to OP, commented in the wrong place hehe

  • Buddy, it worked great. Thanks for the help, I recopied your code and I got it. Thanks a lot

  • @Don’t forget to mark the answer as correct so it can be used by people with similar doubt

  • Currently using what? This Audioclip is outdated.

Show 7 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.