0

I am usinf the JavaFx method of playing music files but it isn't working (sound not playing). I feel the problem lies in my files location. Where do I put the .mp3 in my java projects folder for it to be referenced with a simple string as so? Or is there another way to reference it? JavaFX Media takes a String parameter.

String test = "test.mp3";
Media x = new Media(test);
MediaPlayer mediaPlayer = new MediaPlayer(x);
mediaPlayer.play();
Jhon Mrag
  • 27
  • 4
  • have you already tried passing in the file path along with the file? like "C:/Users/You/Documents/Java Projects/Project 1/test.mp3" – wbrugato Apr 08 '16 at 22:49
  • Yes, it gave me an error mentioning illegal characters. I have a resource folder that i added in my referenced libraries which i am able to reference files in there regardless of the hard drive the program is run on but that also doesn't work in this case. – Jhon Mrag Apr 08 '16 at 23:29

1 Answers1

0

If you have read the JavaDoc of Media, then you know that you have to give a http, file or jar URI to the constructor you are using.
Actually from looking at the source code I wonder that you are not getting an IllegalArgumentException.

However, use Class.getResource(...).toURI().toString() to get the String you want to give to the Media constructor.
The combination of which Class object you call this on and what you give to the getResource() method depends on how you layout your files.
If you have your file besides your class, getClass().getResource("file.name") should work.
If you have your file in the root of your classpath, getClass().getResource("/file.name") should do.

You can give any other valid http, file or jar URI to the contructor too of course.

Vampire
  • 35,631
  • 4
  • 76
  • 102
  • Heres my full method public static void playSong() String test = getClass().getResource("test2.mp3").toURI().toString(); Media x = new Media(test); MediaPlayer mediaPlayer = new MediaPlayer(x); mediaPlayer.play(); } Under getClass(), it gives an error Cannot make a static reference to the non-static method getClass() from the type Object. I put the test2.mp3 file in the same package as my Sound class(the class that contains this method). Sorry about this weird comment. I'm new to this website – Jhon Mrag Apr 10 '16 at 01:16
  • Well, if you are in static context, do not use `getClass()`, but `YourClassName.class` instead. – Vampire Apr 10 '16 at 01:54
  • Thanks for the help, it worked. For those viewing this and having the problem of Toolkit not being initialized, refer to this: http://tech.chitgoks.com/2013/05/11/how-to-fix-toolkit-not-initialized-error-in-java-fx/#comment-9240 And for those having trouble with MediaPlayer muting after 5 seconds, refer to this: http://stackoverflow.com/questions/6241687/mediaplayer-stop-playing-after-about-5-seconds – Jhon Mrag Apr 10 '16 at 03:19