经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 移动开发 » Android » 查看文章
Android 使用URLConnection下载音频文件
来源:cnblogs  作者:RustFisher  时间:2019/9/25 9:09:21  对本文有异议

本文链接: Android 使用URLConnection下载音频文件

使用MediaPlayer播放在线音频,请参考Android MediaPlayer 播放音频

有时候我们会需要下载音频文件。这里提供一种思路,将在线音频文件通过流写到本地文件中。
使用URLConnection来建立连接,获取到的数据写到文件中。

URLConnection建立连接后,可以获取到数据长度。由此我们可以计算出下载进度。

  1. public class DownloadStreamThread extends Thread {
  2. String urlStr;
  3. final String targetFileAbsPath;
  4. public DownloadStreamThread(String urlStr, String targetFileAbsPath) {
  5. this.urlStr = urlStr;
  6. this.targetFileAbsPath = targetFileAbsPath;
  7. }
  8. @Override
  9. public void run() {
  10. super.run();
  11. int count;
  12. File targetFile = new File(targetFileAbsPath);
  13. try {
  14. boolean n = targetFile.createNewFile();
  15. Log.d(TAG, "Create new file: " + n + ", " + targetFile);
  16. } catch (IOException e) {
  17. Log.e(TAG, "run: ", e);
  18. }
  19. try {
  20. URL url = new URL(urlStr);
  21. URLConnection connection = url.openConnection();
  22. connection.connect();
  23. int contentLength = connection.getContentLength();
  24. InputStream input = new BufferedInputStream(url.openStream());
  25. OutputStream output = new FileOutputStream(targetFileAbsPath);
  26. byte[] buffer = new byte[1024];
  27. long total = 0;
  28. while ((count = input.read(buffer)) != -1) {
  29. total += count;
  30. Log.d(TAG, String.format(Locale.CHINA, "Download progress: %.2f%%", 100 * (total / (double) contentLength)));
  31. output.write(buffer, 0, count);
  32. }
  33. output.flush();
  34. output.close();
  35. input.close();
  36. } catch (Exception e) {
  37. Log.e(TAG, "run: ", e);
  38. }
  39. }
  40. }

启动下载,即启动线程。

  1. new DownloadStreamThread(urlStr, targetFileAbsPath).start();

值得注意的是,如果本地已经有了文件,需要做一些逻辑判断。例如是否删掉旧文件,重新下载。或是判断出已有文件,中止此次下载任务。
例如可以用connection.getContentLength()与当前文件长度来比较,如果不一致,则删掉本地文件,重新下载。

实际上,URLConnection能处理很多流媒体。在这里是用来下载音频文件。可以实现下载功能和类似“边下边播”的功能。

代码可以参考示例工程: https://github.com/RustFisher/android-MediaPlayer

原文链接:http://www.cnblogs.com/rustfisher/p/11576548.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号