当我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);
}
}
}
1条答案
按热度按时间yjghlzjz1#
如果没有实际运行的JavaFX运行时,就不能使用
MediaPlayer
,通常通过调用Application.launch()
来确保运行。下面是一个简单的例子,它将工作:根据应用程序正在执行的其他操作,了解
start()
是在FX应用程序线程上执行的可能很重要