我正在尝试使用MediaPlayer播放音频文件,但它无法正常显示
Exception in thread "main" java.lang.IllegalArgumentException: uri.getScheme() == null! uri == 'audio.mp3'
任何人都可以帮我解决这个问题吗?
这是我的代码:
package playaudio;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
public class PlayAudio {
public static void main(String[] args) {
String fileName = "audio.mp3";
Media playFile = new Media(fileName);
MediaPlayer mediaPlayer = new MediaPlayer(playFile);
mediaPlayer.play();
}
}
编辑:当我尝试将文件名转换为URI时,它会显示以下异常。
Exception in thread "Thread-0" java.lang.IllegalStateException: Toolkit not initialized
代码:
package playaudio;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
public class PlayAudio {
public static void main(String[] args) {
String fileName = "audio.mp3";
Media playFile = new Media(Paths.get(fileName).toUri().toString());
MediaPlayer mediaPlayer = new MediaPlayer(playFile);
mediaPlayer.play();
}
}
答案 0 :(得分:1)
你可以试试这个。
InputStream in = new FileInputStream("audio.wav");
AudioStream as = new AudioStream(in);
AudioPlayer.player.start(as);
但是,这只适用于.wav文件。
答案 1 :(得分:0)
Media
的构造函数实际上需要一个URI,这意味着你必须将文件名转换为URI,试试这个:
Media media = new Media(Paths.get(fileName).toUri().toString());