从 Webstream 使用 JAAD 播放 AAC

play AAC with JAAD from Webstream

我需要用我的 Java 应用程序播放 AAC 编码的音频。 我阅读了 ,它展示了如何播放一组文件。 但是,当我的源是网络流时,我该如何播放 AAC?

从你给出的例子来看,它使用MP4Container

来自JAAD的代码:

public MP4Container(InputStream in) throws IOException {
    this.in = new MP4InputStream(in);
    boxes = new ArrayList<Box>();

    readContent();
}

public MP4Container(RandomAccessFile in) throws IOException {
    this.in = new MP4InputStream(in);
    boxes = new ArrayList<Box>();

    readContent();
}

示例使用 MP4Container(RandomAccessFile in) 构造函数,而您必须使用此 MP4Container(InputStream in),其中 in 将是来自套接字的输入流。

以下是使用 JAAD 播放原始 AAC 的解决方案:

public class AACPlayer extends AbstractPlayer implements Runnable {
private Thread runnerThread;
@Override
public void stop() {
    stop = true;
    GUIHandler.getInstance().resetComponents();
}

@Override
public void play() {
    stop = false;
    if(!runnerThread.isAlive()) {
        runnerThread = new Thread(this);
        runnerThread.start();
    }
}

@Override
public void setUrl(URL url) {
    this.url = url;
}

@Override
public void run() {
    decodeAndPlayAAC();
}

private void decodeAndPlayAAC() {
    SourceDataLine line = null;
    byte[] b;
    try {
        isPlaying = true;
        final ADTSDemultiplexer adts = new ADTSDemultiplexer(url.openStream());
        final Decoder dec = new Decoder(adts.getDecoderSpecificInfo());
        final SampleBuffer buf = new SampleBuffer();
        while(!stop) {
            b = adts.readNextFrame();
            dec.decodeFrame(b, buf);

            if(line==null) {
                final AudioFormat aufmt = new AudioFormat(buf.getSampleRate(), buf.getBitsPerSample(), buf.getChannels(), true, true);
                line = AudioSystem.getSourceDataLine(aufmt);
                line.open();
                line.start();
            }
            b = buf.getData();
            line.write(b, 0, b.length);
        }
    } catch (LineUnavailableException e) {
        e.printStackTrace();
    } catch (AACException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(line!=null) {
            line.stop();
            line.close();
            isPlaying = false;
        }
    }
}

}