Android - 直接从输入流播放 mp3 而不写入临时文件

Android - Playing mp3 directly from the input stream without writing into temp files

我正在创建一个输入流来缓冲和流式传输来自云端的 mp3。

URL url = new URL("http://xxxx.yyy.com/Demo.mp3");

InputStream inputStream = url.openStream();

现在如何从媒体播放器播放 mp3 而无需使用临时文件来存储它并从中读取?我正在为 Android Lollipop

开发

我很确定 MediaPlayer 可以处理远程 URL。看看 MediaPlayer class 中的 this example. Check the setDataSource 方法。

编辑:因为您真的很想使用输入流,所以我认为您需要进入低级别。检查可能相关的 AudioTrack class. This SO answer might help. There are also a couple of issues here and here

这个问题直到今天仍然存在!!!检查这些 link 出 https://code.google.com/p/android/issues/detail?id=29870

http://www.piterwilson.com/blog/2014/03/11/android-mediaplayer-not-quite-there-yet/。 绝对没有办法访问和控制 MediaPlayer 缓冲区,也没有办法将存储在字节数组中的缓冲 mp3 内容作为参数提供给 MediaPplayer 来播放它。所以人们要么将 mp3 缓冲区转换为 PCM 并使用 AudioTrack 播放它,要么将输入流的字节数组写入本地套接字,然后使用套接字文件描述符让 Mediaplayer 回读,如下所述 link Audio stream buffering

我用来将二进制数据直接提供给 MediaPlayer 的解决方案是使用 ParcelFileDescriptor#createPipe() (API level 9) and MediaPlayer#setDataSource(java.io.FileDescriptor).

这是示例代码(未经测试):

ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe();
FileDescriptor fd = pipe[0].getFileDescriptor();
mediaPlayer.setDataSource(fd);
OutputStream out = new ParcelFileDescriptor.AutoCloseOutputStream(pipe[1]);

从现在开始,您在输出流中写入的任何内容都将被 MediaPlayer 接收。这非常快,因为它使用内核 FIFO 来传输数据(没有套接字,没有 TCP),据我所知,它完全在 RAM 中(没有使用实际文件)。