1

I would like to use JavaFX media player to play mp3 without any GUI.

I saw a lot of examples online, but all of them create JFX Frames.

When I run following code:

protected static void playSong(){
    String bip = "file:///c:/a/a.mp3"; 
    Media hit = new Media(bip);
    MediaPlayer mediaPlayer = new MediaPlayer(hit);
    mediaPlayer.play();
    System.out.print(true);
}

I get:

java.lang.IllegalStateException: Toolkit not initialized

Daniil Shevelev
  • 11,739
  • 12
  • 50
  • 73
  • thank you. that answer is helpful. I will post complete solution that solved my problem below. – Daniil Shevelev Feb 23 '14 at 14:07
  • 1
    This question is absolutely **not** a duplicate of the linked question. That question is about running sound clips *in the background*. In the background is not at all the same as running in an app with no GUI, which is what this is about. As far as I can tell, all answers to the supposed duplicate require a UI application. – Nate Jan 19 '20 at 23:47
  • @Nate definitely a duplicate - doesn't really matter how/why the toolkit isn't initialized as it must be ;) – kleopatra Jan 20 '20 at 10:49
  • @kleopatra, Nope, that's completely incorrect. An application that **has a GUI** can minimize that GUI, run in the background, and want to play a sound without reshowing any GUI. Another application may be entirely non-graphical and **never** show any UI. The answers which then require various APIs only available in GUI applications are not applicable to the second scenario, or would require a major reworking of what is currently a pure background daemon. FTR, I have the second problem, which is how I found this Q, and the dupe's answers are useless to me. – Nate Jan 22 '20 at 08:39
  • @Nate bottom line is, that you _must_ initialize the toolkit .. that's what all the answers (the self-answer here and those in the dupe) do. Having a UI or not is irrevant (and actuall, none of the answers have any) – kleopatra Jan 22 '20 at 09:45

1 Answers1

1

Following worked for me:

import javafx.application.Application;
import javafx.stage.Stage;

public class App extends Application {
    public static void main(String[] args) {
        Application.launch();
    }

    @Override
    public void start(Stage arg0) throws Exception {
        playSong();
    }
}
Nate
  • 31,017
  • 13
  • 83
  • 207
Daniil Shevelev
  • 11,739
  • 12
  • 50
  • 73