如何将FileDescriptor与HTTP URL一起使用

Mik*_*ery 8 android file-descriptor file-uri

我希望这可以让Android MediaPlayer使用身份验证从URL流式传输,但现在我不太确定.我没有问题让它从开放服务器流(没有身份验证),但我没有看到任何方式告诉MediaPlayer使用基本身份验证,除非使用该FileDescriptor参数工作?所以我尝试了这个,但得到了以下错误:

IllegalArgumentException: Expected file scheme in URI http://www.myserver.com/music.mp3
Run Code Online (Sandbox Code Playgroud)

我的代码看起来像这样:

File f = new File(new URL("http://www.myserver.com/music.mp3").toURI());
FileInputStream fis = new FileInputStream(f);
mediaplayer.SetDataSource(fis.getFD());
Run Code Online (Sandbox Code Playgroud)

说a FileDescriptor只能用于本地file://URL而不是普通的http://URL 是否正确?如果是这样,有没有人对如何从需要使用Android进行身份验证的服务器进行流式传输有任何其他想法MediaPlayer

rds*_*rds 0

FileDescriptor 只能与本地 file:// URL 一起使用,这样说是否正确

不,这是不正确的,Java 采用了“一切皆文件”的 Unix 哲学,并且javadoc 如下

代表打开文件、打开套接字或其他字节源或接收器的底层机器特定结构的句柄。

但是,MediaPlayer只能打开可查找的文件描述符setDataSource(FileDescriptor)

也许你可以尝试这样的事情(未经测试)

URLConnection connection = new URL(url).openConnection();
// Authenticate the way you can
connection.setRequestProperty("HeaderName", "Header Value");

// Save into a file
File tmp = new File(getCacheDir(), "media");
InputStream in = connection.getInputStream();
FileOutputStream out = new FileOutputStream(tmp);
// TODO copy in into out
mediaPlayer.setDataSource(tmp);
Run Code Online (Sandbox Code Playgroud)