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

总结

以上所述是小编给大家介绍的Android 使用URLConnection下载音频文件的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对创新互联网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

当前题目:Android使用URLConnection下载音频文件的方法
文章路径:https://www.cdcxhl.com/article28/ihicjp.html

成都网站建设公司_创新互联,为您提供企业网站制作标签优化网站改版用户体验小程序开发营销型网站建设

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

营销型网站建设