android - 使用 okhttp 下载 mp3 文件会产生损坏的文件
问题描述
我正在尝试从 http 链接下载 mp3 文件并将文件保存到本地存储。我尝试过的所有代码都会保存一个损坏的文件,该文件的大小是应有的两倍。文件应该是 1,204,787 保存的文件是 2,478,272
我要下载的文件是:rise-stage.bioinf.unc.edu/cue_audio/sampleaudio.mp3 –</p>
手动下载时播放正常。
fun downloadFilea(url:String , localFileName:String)
{
val request: Request = Request.Builder()
.url(url)
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
println("error"+e.toString())
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
if (!response.isSuccessful) throw IOException("Unexpected code $response")
var uri = dataMgr.getLocalURI(localFileName)
var file = File(uri)
val body = response.body
val contentLength = body!!.contentLength()
val source = body.source()
val DOWNLOAD_CHUNK_SIZE:Long = 2048
val sink: BufferedSink = file.sink().buffer()
var totalRead: Long = 0
var read: Long = 0
while (source.read(sink.buffer(), DOWNLOAD_CHUNK_SIZE).also {
read = it
} != -1L) {
totalRead += read
val progress = (totalRead * 100 / contentLength).toInt()
}
sink.writeAll(source)
sink.flush()
sink.close()
Log.d(logTag, "downloaded file")
}
})
}
解决方案
可能是下载站点坏了,尝试手动访问。
推荐阅读
- amazon-web-services - 解密 AWS 托管密钥
- c# - 如何使用 DI usinq autofac .net 框架注册 ILogger(Microsoft.Extensions.Logging)
- centos - 无法在 CentOS 上安装 Review board
- java - 为什么我得到空括号作为对 http GET 请求的响应
- mysql - 选择给定日期时间在另外两个之间的行不起作用
- r - R中cmdscale的意外结果
- three.js - EdgesGeometry 不显示任何内容?
- c - 如何检查文件权限中的“+”?(ACL)
- google-apps-script - 如何丢弃草稿并在谷歌应用脚本中实时更新
- cucumber - 黄瓜正则表达式步骤定义