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能处理很多流媒体。在这里是用来下载音频文件。可以实现下载功能和类似“边下边播”的功能。
代码可以参考示例工程: https://github.com/RustFisher/android-MediaPlayer
一个软件工程师的记录
分类:
Android-101
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端