我有一个应用程序正在播放可在公共URL上使用的MP3文件。不幸的是,服务器不支持流媒体,但Android使用户体验完全可以接受。
除了JellyBean之外,所有平台都能正常运行。在请求MP3时,JB请求范围标题10次。只有在第10次尝试之后,它才会恢复到原来的行为。 Looks like this already reported issue。
我找到了另一个SO thread,其中推荐的解决方案是使用 Tranfer-Encoding:chunked 标头。但就在下面,有一条评论认为这不起作用。
目前我无法控制上述响应标题,但在我能够做到这一点之前,我想在客户端搜索替代方案。 (即便如此,我只能返回包含从0到Content-Length的索引的Content-Range - 1. Ex.Content-Range:bytes 0-3123456 / 3123457)。
我尝试做的是通过以下方式在客户端实现伪流式传输:
可以在那里找到进行解码的代码段,我只修改了它以便接收一个InputStream:
public byte[] decode(InputStream inputStream, int startMs, int maxMs) throws IOException {
ByteArrayOutputStream outStream = new ByteArrayOutputStream(1024);
float totalMs = 0;
boolean seeking = true;
try {
Bitstream bitstream = new Bitstream(inputStream);
Decoder decoder = new Decoder();
boolean done = false;
while (!done) {
Header frameHeader = bitstream.readFrame();
if (frameHeader == null) {
done = true;
} else {
totalMs += frameHeader.ms_per_frame();
if (totalMs >= startMs) {
seeking = false;
}
if (!seeking) {
// logger.debug("Handling header: " + frameHeader.layer_string());
SampleBuffer output = (SampleBuffer) decoder.decodeFrame(frameHeader, bitstream);
if (output.getSampleFrequency() != 44100 || output.getChannelCount() != 2) {
throw new IllegalArgumentException("mono or non-44100 MP3 not supported");
}
short[] pcm = output.getBuffer();
for (short s : pcm) {
outStream.write(s & 0xff);
outStream.write((s >> 8) & 0xff);
}
}
if (totalMs >= (startMs + maxMs)) {
done = true;
}
}
bitstream.closeFrame();
}
return outStream.toByteArray();
} catch (BitstreamException e) {
throw new IOException("Bitstream error: " + e);
} catch (DecoderException e) {
throw new IOException("Decoder error: " + e);
}
}
我在时间块中请求解码的字节:从(0,5000)开始,所以我将首先播放一个更大的数组,然后我请求跨越一秒的下一个字节数组:(5000,1000 ),(6000,1000),(7000,1000)等
解码速度足够快,并且在另一个线程中完成,一旦解码的字节数组可用,我就使用阻塞队列将其写入正在另一个线程中播放的AudioTrack。
问题是播放不顺畅,因为块在轨道中不连续(每个块都是连续的,但在AudioTrack中添加会导致播放不顺利)。
总结:
谢谢!
答案 0 :(得分:2)
看起来您正在尝试开发自己的流式传输类型。这可能会导致块状或中断播放,因为您必须尝试连续的信息管道,而不需要用完的字节来读取。
基本上,您必须考虑普通流媒体客户端负责的所有情况。例如,有时某些块可能在传输中丢失或丢失;有时音频播放可能会赶上下载; cpu开始滞后,影响播放;等等。
如果你想继续沿着这条路走下去研究的话就是Sliding Window实现,它本质上是一种抽象的技术,试图保持网络连接始终活跃和流畅。你应该能够通过谷歌找到几个例子,这里是一个开始的地方:http://en.wikipedia.org/wiki/Sliding_window_protocol
修改:在修复此问题之前,可以帮助您的一种解决方法是将SDK< 16中的MediaPlayer.java
和AudioManager.java
的源代码包含到您的项目中,看看是否能解决问题。如果您没有源代码,可以使用SDK Manager下载它。
答案 1 :(得分:1)
AudioTrack本质上是从文档(Will block until all data has been written to the audio mixer.
)中阻止的。我不确定你是否正在从文件中读取并在同一个线程中写入AudioTrack;如果是这样,那么我建议你为AudioTrack启动一个线程。