Search code examples
javaaudiojavafxmedia-player

JavaFX - MediaPlayer Not Working


package main;

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.event.ActionEvent;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import java.io.File;
import javafx.scene.media.AudioClip;


public class Controller {
Media sound = new Media("mouseHover.mp3");
MediaPlayer mediaPlayer = new MediaPlayer(sound);
mediaPlayer.play();
}

I'm trying to play the sound file, but the error I'm getting is "cannot resolve symbol play" and my IDE also says that "mediaPlayer" is never even used. Why is this? I'm pretty sure the path to my media is correct (I put it in the root file next to src).


Solution

  • This is a class, you need to execute mediaPlayer.play() in your main function of the app.

    public class Controller {
        Media sound = new Media("mouseHover.mp3");
        MediaPlayer mediaPlayer = new MediaPlayer(sound);
        //Empty constructor
        public Controller()
        {
        }
    }
    

    In your main function of the app you play it like this :

    public static void main(String [] args)
    {
           Controller ct = new Controller();
           ct.mediaPlayer.play();
    }