我正在编写一个可以从 Http 播放的小型播放器。媒体播放器可以使用mPlayer.setDataSource(url) 从 http 流播放 mp3;,但我想保存这个文件。我试过以下:
public static void downloadFile(File f, String songUrl, IDownloadListener listener)throws Exception{
URL url = new URL(songUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
connection.setDoInput(true);
InputStream inStream = connection.getInputStream();
FileOutputStream outStream = new FileOutputStream(f);
Integer fileLength = connection.getContentLength();
try {
byte data[] = new byte[16384];
int lastPercentNotify = -1, curPercent;
int count;
int total = 0;
listener.onFileDescriptorAvailable(outStream.getFD()); //!!!! this willnotify about FD
while ((count = inStream.read(data, 0, data.length)) != -1){
total += count;
outStream.write(data, 0, count);
curPercent = (total * 100) / fileLength;
if (curPercent != lastPercentNotify && listener != null && curPercent % 10 == 0){
listener.onDownload(f.getName(), curPercent, 100);
lastPercentNotify = curPercent;
}
}
}finally {
inStream.close();
outStream.close();
}
}
在我的听众中,我做了以下事情:
mPlayer.setDataSource(fileDescr);
//prepare and call mPlayer.start()
但是当我尝试更改获取描述符时的点时,我有各种例外情况。
UPD:我的代码可以很好地保存文件。我在播放 mp3 和同时保存到 SD 卡时遇到了麻烦。