Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Playing MP3 in chunks with Java?

Tags:

java

stream

mp3

Sadly MP3 support within Java is lacking. I am developing an app that needs to receive chunks of MP3 and play them. I was using Jlayer MP3 library like this:

import javazoom.jl.player.Player;
public class MP3 {
    private String filename;
    private Player player; 

    // constructor that takes the name of an MP3 file
    public MP3(String filename) {
        this.filename = filename;
    }

    public void close() { if (player != null) player.close(); }

    // play the MP3 file to the sound card
    public void play() {
        try {
            FileInputStream fis     = new FileInputStream(filename);
            BufferedInputStream bis = new BufferedInputStream(fis);
            player = new Player(bis);
        }
        catch (Exception e) {
            System.out.println("Problem playing file " + filename);
            System.out.println(e);
        }

        player.play();
}

But my problem is that I have only chunks of the full MP3 file, and I need to play them as they arrive. Is there any better alternative?

Edit

Found an interesting similar question: MP3 won't stream with JMF Also: Decoding MP3 files with JLayer

like image 294
dynamic Avatar asked Feb 10 '14 14:02

dynamic


1 Answers

Create a class that implements InputStream, and works to receive the chunks as they arrive, but serves up the bytes to the player. Just make sure to track where you are in each chunk as it requests bytes and then discard the chunk when you've burned through it and start serving up data from the next one.

Since the player expects to deal with an InputStream, it will be none the wiser. You probably won't need to wrap that in a BufferedInputStream since you'll be handling that in your class.

like image 60
Bill Avatar answered Sep 26 '22 03:09

Bill