java 工具包未初始化

cetgtptt  于 2023-06-04  发布在  Java
关注(0)|答案(1)|浏览(212)

当我truing播放声音在mp3格式,代码throwes我错误:“线程“main”中出现异常java.lang.IllegalStateException:工具包未初始化”。

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);
        }
    }
}
yjghlzjz

yjghlzjz1#

如果没有实际运行的JavaFX运行时,就不能使用MediaPlayer,通常通过调用Application.launch()来确保运行。下面是一个简单的例子,它将工作:

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);
        }
    }
}

根据应用程序正在执行的其他操作,了解start()是在FX应用程序线程上执行的可能很重要

相关问题