音频文件没有在java中播放

时间:2022-07-23 19:41:44

I'm trying to play an audio file using MediaPlayer but it's not working and showing

我正在尝试使用MediaPlayer播放音频文件,但它无法正常显示

Exception in thread "main" java.lang.IllegalArgumentException: uri.getScheme() == null! uri == 'audio.mp3'

Can anyone help me to fix this ?

任何人都可以帮我解决这个问题吗?

Here is my code:

这是我的代码:

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

}

EDIT: When i try converting the filename to a URI it shows following exception.

编辑:当我尝试将文件名转换为URI时,它显示以下异常。

Exception in thread "Thread-0" java.lang.IllegalStateException: Toolkit not initialized

Code:

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

}

2 个解决方案

#1


1  

You can try this.

你可以试试这个。

InputStream in = new FileInputStream("audio.wav");
AudioStream as = new AudioStream(in);     
AudioPlayer.player.start(as);

But, this will only work for .wav files.

但是,这只适用于.wav文件。

#2


0  

The constructor for Media actually requires a URI, meaning that you will have to convert the filename to a URI, try this:

Media的构造函数实际上需要一个URI,这意味着你必须将文件名转换为URI,试试这个:

Media media = new Media(Paths.get(fileName).toUri().toString());

媒体媒体=新媒体(Paths.get(fileName).toUri()。toString());

#1


1  

You can try this.

你可以试试这个。

InputStream in = new FileInputStream("audio.wav");
AudioStream as = new AudioStream(in);     
AudioPlayer.player.start(as);

But, this will only work for .wav files.

但是,这只适用于.wav文件。

#2


0  

The constructor for Media actually requires a URI, meaning that you will have to convert the filename to a URI, try this:

Media的构造函数实际上需要一个URI,这意味着你必须将文件名转换为URI,试试这个:

Media media = new Media(Paths.get(fileName).toUri().toString());

媒体媒体=新媒体(Paths.get(fileName).toUri()。toString());