在java中播放mp3

时间:2015-01-10 04:07:19

标签: java mp3 media-player

我正在开发一个涉及播放mp3文件的Java项目。我希望我的应用程序播放项目中的文件,因此我将音乐文件存储在名为music的文件夹中,该文件夹位于名为resources的源文件夹中。这是我现在的代码,但是当我运行它时,我得到比特流错误代码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();

}

3 个答案:

答案 0 :(得分:0)

在设置播放器

之前尝试关闭BufferedInputStream
bis.close();

我发现了类似的问题here

答案 1 :(得分:0)

我实际上发现了我的问题,这是一件小事,我很尴尬!事实证明,当我删除路径名前面的前导“/”时,我的代码运行正常。我相信这与绝对路径与相对路径有关。

答案 2 :(得分:0)

使用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");
        }
    }
}