首页 > 解决方案 > 使用 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")
        }
    })
}

标签: androidkotlinokhttp

解决方案


可能是下载站点坏了,尝试手动访问。


推荐阅读