-1

When i truing to play sound in mp3 format, code throwes me error: "Exception in thread "main" java.lang.IllegalStateException: Toolkit not initialized".

import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;

import java.io.*;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

public class Main {
    public static void main(String[] args) {
        new Main();
    }
    
    int id = 467339;

    public Main(){
        try {
            downloadFile(new URL("https://www.newgrounds.com/audio/download/"+id),id+".mp3");
            Media media = new Media(new File(id+".mp3").toURI().toString());
            MediaPlayer mediaPlayer = new MediaPlayer(media);
            mediaPlayer.play();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void downloadFile(URL url, String outputFileName) throws IOException {
        try (InputStream in = url.openStream();
             ReadableByteChannel rbc = Channels.newChannel(in);
             FileOutputStream fos = new FileOutputStream(outputFileName)) {
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        }
    }
}

1 Answers1

4

You can't use a MediaPlayer without the JavaFX runtime actually running, which you typically ensure with a call to Application.launch(). Here is a simple example which will work:

import javafx.application.Application;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

public class Main extends Application {
    public static void main(String[] args) {
        Application.launch(args);
    }
    
    int id = 467339;

    @Override
    public void start(Stage stage){
        try {
            downloadFile(new URL("https://www.newgrounds.com/audio/download/"+id),id+".mp3");
            Media media = new Media(new File(id+".mp3").toURI().toString());
            MediaPlayer mediaPlayer = new MediaPlayer(media);
            mediaPlayer.play();
        } catch (IOException e) {
            e.printStackTrace();
        }
        stage.show();
    }

    public void downloadFile(URL url, String outputFileName) throws IOException {
        try (InputStream in = url.openStream();
             ReadableByteChannel rbc = Channels.newChannel(in);
             FileOutputStream fos = new FileOutputStream(outputFileName)) {
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        }
    }
}

Depending what else your application is doing, it may be important to know that start() is executed on the FX Application Thread

James_D
  • 201,275
  • 16
  • 291
  • 322