前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android 使用URLConnection下载音频文件

Android 使用URLConnection下载音频文件

作者头像
AnRFDev
发布2021-02-01 15:20:51
8560
发布2021-02-01 15:20:51
举报
文章被收录于专栏:AnRFDevAnRFDev

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

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

有时候我们会需要下载音频文件。这里提供一种思路,将在线音频文件通过流写到本地文件中。

使用URLConnection来建立连接,获取到的数据写到文件中。

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

代码语言:javascript
复制
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);
        }
    }
}

启动下载,即启动线程。

代码语言:javascript
复制
new DownloadStreamThread(urlStr, targetFileAbsPath).start();

值得注意的是,如果本地已经有了文件,需要做一些逻辑判断。例如是否删掉旧文件,重新下载。或是判断出已有文件,中止此次下载任务。

例如可以用connection.getContentLength()与当前文件长度来比较,如果不一致,则删掉本地文件,重新下载。

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

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

更多参考:

Android MediaPlayer 基础简介

Android MediaPlayer 播放音频

Android 使用URLConnection下载音频文件

Android MediaPlayer 音频倍速播放,调整播放速度

Android音视频相关文章请参考 https://rustfisher.com/tags/Android-Media/

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档