在 java 中播放 mp3

Playing a mp3 in java

我正在做一个涉及播放 mp3 文件的 Java 项目。我希望我的应用程序播放项目中的文件,因此我将音乐文件存储在名为 music 的文件夹中,该文件夹位于名为资源的源文件夹中。这是我现在拥有的代码,但是当我 运行 它时,我得到一个 比特流错误代码 102。我似乎无法弄清楚出了什么问题,有什么帮助吗?我正在使用 javazoom 库 (javazoom.jl.player.Player)

public void play() {
    try {
        InputStream stream = MP3.class.getClassLoader()
                .getResourceAsStream("/music/LoveStory.mp3");
        BufferedInputStream bis = new BufferedInputStream(stream);
        player = new Player(bis);
    } catch (Exception e) {
        System.out.println("Problem playing file " + filename);
        System.out.println(e);
    }

    // run in new thread to play in background
    new Thread() {
        public void run() {
            try {
                player.play();
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }.start();

}

尝试在设置播放器之前关闭 BufferedInputStream

bis.close();

我发现了类似的问题here

其实我也发现了我的问题,这么小的事我还挺尴尬的!事实证明,当我删除路径名前面的前导“/”时,我的代码 运行 很好。我相信这与绝对路径与相对路径有关。

使用JavaFX环境:

package be.saleconix;

import java.net.URL;

import com.sun.javafx.application.PlatformImpl;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.util.Duration;

class AudioPlayer implements Runnable {
    private URL resource;
    private Media media;
    private MediaPlayer mediaPlayer;
    private boolean ready = false;
    private Thread t;
    private String threadname;
    private static Integer numberOfActiveThreads = 0;

    /**
     * Start a mediaplayer thread
     * @param filename
     * @param threadname
     * @throws NullPointerException
     * @throws InterruptedException
     */
    public AudioPlayer(String filename, String threadname) throws NullPointerException, InterruptedException {
        if (numberOfActiveThreads == 0) {
            PlatformImpl.startup(()->{}); // initialize JavaFX environment
            System.out.println("The JavaFX environment has been started");
        }
        this.threadname = threadname;
        resource = getClass().getResource("/" + filename);
        media = new Media(resource.toString());
        t = new Thread(this, threadname);
        t.start();
        numberOfActiveThreads ++;
    }

    public void run() {
        mediaPlayer = new MediaPlayer(media);
        mediaPlayer.setOnReady(() -> { // register a callback and let it deregister itself after execution
            System.out.println("The mediaplayer [" + threadname + "] has been started");
            ready = true;
            mediaPlayer.setOnReady(null);
        });
        while (!t.isInterrupted());
        System.out.println("The mediaplayer [" + threadname + "] has been terminated");
    }

    String getThreadname() {
        return threadname;
    }

    /**
     * Plays the sound from the start
     * @throws InterruptedException
     */
    void play() throws InterruptedException {
        play(0);
    }

    /**
     * Plays the sound at a specific position in ms
     * @throws InterruptedException
     * @throws IllegalThreadStateException
     */
    void play(double position) throws InterruptedException, IllegalThreadStateException {
        int i = 500;
        while (!ready && i > 0) {
            Thread.sleep(1);
            i--;
        }
        if (i > 0) {
            mediaPlayer.setStartTime(Duration.millis(position));
            if (mediaPlayer.getStatus() == MediaPlayer.Status.PLAYING) {
                mediaPlayer.setOnStopped(()->{
                    mediaPlayer.play();
                    mediaPlayer.setOnStopped(null);
                });
                mediaPlayer.stop();
            } else {
                mediaPlayer.play();
            }
        } else {
            throw new IllegalThreadStateException("The mediaplayer is not ready after 500ms timeout");
        }
    }

    /**
     * Stop the mediaplayer thread
     */
    void stop() {
        mediaPlayer.setOnReady(null);
        mediaPlayer.setOnStopped(null);
        mediaPlayer.stop();
        numberOfActiveThreads --;
        t.interrupt();
        if (numberOfActiveThreads == 0) {
            PlatformImpl.exit(); // exit the JavaFX environment
            System.out.println("The JavaFX environment has been exited");
        }
    }

}

public class Main {
    public static void main(String[] args) {
        try {
            AudioPlayer audioPlayerA = new AudioPlayer("test.mp3", "audioplayerA");

            System.out.println("Play audioplayerA from start");
            audioPlayerA.play();

            System.out.println("Waiting 10s ...");
            Thread.sleep(10000);

            System.out.println("Play audioplayerA at position 20s");
            audioPlayerA.play(20000);

            System.out.println("Waiting 5s ...");
            Thread.sleep(5000);

            AudioPlayer audioPlayerB = new AudioPlayer("test1.mp3", "audioplayerB");

            System.out.println("Play audioplayerB from start.");
            audioPlayerB.play();

            System.out.println("Waiting 20s ...");
            Thread.sleep(20000);

            System.out.println("Stopping audioplayerA");
            audioPlayerA.stop();

            System.out.println("Stopping audioplayerB");
            audioPlayerB.stop();

        } catch (NullPointerException e) {
            System.out.println("Cannot create audio player, check filename.");
        } catch (InterruptedException e) {
            System.out.println("Thread interrupted: " + e);
        } finally {
            System.out.println("Main thread has been exited");
        }
    }
}