Search code examples
javaaudiojavafxmp3media

JavaFX - Playing an mp3


package musictesting;
import java.io.File;
import javafx.scene.media.MediaPlayer; 
import javafx.scene.media.Media; 

public class playsound { 

    public static void testsound(){

       String musicFileName = "ROQUE.mp3"; 
       Media sound = new Media(new File(musicFileName).toURI().toString());
       Media song = new Media(Paths.get(musicFileName).toUri().toString());
       MediaPlayer mediaPlayer = new MediaPlayer(sound);
       mediaPlayer.play();
    }

    public static void main(String [] args){
       testsound();
    }

}

For a group assignment I've been deligated to make the music that plays for a game developed in Java, I've been looking at some ways to play audio files and it seems like JavaFX is the way to go. I just wanted to run like a simple test player but I get the following error:

Exception in thread "main" MediaException: MEDIA_UNAVAILABLE : C:\Users\Dylan\Documents\stuffinaround\musictesting\ROQUE.mp3 (The system cannot find the file specified)
    at javafx.scene.media.Media.<init>(Unknown Source)
    at musictesting.playsound.testsound(playsound.java:13)
    at musictesting.playsound.main(playsound.java:19)

The file ROQUE.mp3 is in my source/bin folders.

I've tried different code people have posted online, this seems pretty straight ahead. What am I doing wrong?

Thanks in advance


Solution

  • Anyone having trouble with this should check out this thread, initializing JavaFX from a separate method or class fixes this, I'm not sure I understand the ins and outs yet but it works for now!

    How to use JavaFX MediaPlayer correctly?