简体   繁体   English

用 Java 分块播放 MP3?

[英]Playing MP3 in chunks with Java?

Sadly MP3 support within Java is lacking.遗憾的是,Java 中缺少 MP3 支持。 I am developing an app that needs to receive chunks of MP3 and play them.我正在开发一个需要接收 MP3 块并播放它们的应用程序。 I was using Jlayer MP3 library like this:我使用 Jlayer MP3 库是这样的:

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.但我的问题是我只有完整的 MP3 文件的大块,我需要在它们到达时播放它们。 Is there any better alternative?有没有更好的选择?

Edit编辑

Found an interesting similar question: MP3 won't stream with JMF Also: Decoding MP3 files with JLayer发现了一个有趣的类似问题: MP3 不会使用 JMF 流式传输另外: 使用 JLayer 解码 MP3 文件

Create a class that implements InputStream, and works to receive the chunks as they arrive, but serves up the bytes to the player.创建一个实现 InputStream 的类,并在块到达时接收块,但将字节提供给播放器。 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.由于播放器希望处理 InputStream,因此它不会更明智。 You probably won't need to wrap that in a BufferedInputStream since you'll be handling that in your class.您可能不需要将它包装在 BufferedInputStream 中,因为您将在类中处理它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM