温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android如何使用URLConnection下载音频文件

发布时间:2021-09-18 17:59:04 来源:亿速云 阅读:128 作者:小新 栏目:编程语言

这篇文章主要为大家展示了“Android如何使用URLConnection下载音频文件”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“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能处理很多流媒体。在这里是用来下载音频文件。可以实现下载功能和类似“边下边播”的功能。

以上是“Android如何使用URLConnection下载音频文件”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI