Reputation: 33
I found below instruction how to play sound in java but while I am trying to use it in Intellij there is no error but at the same nothing happens, did you experience similar issue?
String path = "/Morat.mp3";
Media media = new Media(new File(path).toURI().toString());
MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.play();
Upvotes: 0
Views: 189
Reputation: 7910
Can you show the file structure of your project?
Can you verify that the intended file was found, rather than a new (and empty) file being created at the location you specified?
For a relative path, one omits the starting "/". If you wrote "Morat.mp3" instead of "/Morat.mp3", the code would look for the file in the same folder as the calling code. I'm not exactly clear where "/Morat.mp3" is looking, but I'm guessing it's the root folder for the project.
By the way, it would be good to use URL instead of File, if you have any intention of ever packaging this in a jar.
Upvotes: 0
Reputation: 2513
Code looks okay, so it's hard to say from this point of view.
But I humbly guess, that mediaPlayer
instance got garbage collected before the it has chance to play the mp3
.
Solution
Try to put your mediaPlayer
outside the local scope (e.g. instance or class variable).
Upvotes: 1