本文链接: android 使用urlconnection下载音频文件
使用mediaplayer播放在线音频,请参考android mediaplayer 播放音频
有时候我们会需要下载音频文件。这里提供一种思路,将在线音频文件通过流写到本地文件中。
使用urlconnection来建立连接,获取到的数据写到文件中。
urlconnection建立连接后,可以获取到数据长度。由此我们可以计算出下载进度。
public class downloadstreamthread extends thread { string urlstr; final string targetfileabspath; public downloadstreamthread(string urlstr, string targetfileabspath) { this.urlstr = urlstr; this.targetfileabspath = targetfileabspath; } @override public void run() { super.run(); int count; file targetfile = new file(targetfileabspath); try { boolean n = targetfile.createnewfile(); log.d(tag, "create new file: " + n + ", " + targetfile); } catch (ioexception e) { log.e(tag, "run: ", e); } try { url url = new url(urlstr); urlconnection connection = url.openconnection(); connection.connect(); int contentlength = connection.getcontentlength(); inputstream input = new bufferedinputstream(url.openstream()); outputstream output = new fileoutputstream(targetfileabspath); byte[] buffer = new byte[1024]; long total = 0; while ((count = input.read(buffer)) != -1) { total += count; log.d(tag, string.format(locale.china, "download progress: %.2f%%", 100 * (total / (double) contentlength))); output.write(buffer, 0, count); } output.flush(); output.close(); input.close(); } catch (exception e) { log.e(tag, "run: ", e); } } }
启动下载,即启动线程。
new downloadstreamthread(urlstr, targetfileabspath).start();
值得注意的是,如果本地已经有了文件,需要做一些逻辑判断。例如是否删掉旧文件,重新下载。或是判断出已有文件,中止此次下载任务。
例如可以用connection.getcontentlength()与当前文件长度来比较,如果不一致,则删掉本地文件,重新下载。
实际上,urlconnection能处理很多流媒体。在这里是用来下载音频文件。可以实现下载功能和类似“边下边播”的功能。
代码可以参考示例工程: https://github.com/rustfisher/android-mediaplayer
如对本文有疑问, 点击进行留言回复!!
网友评论