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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With