Kotlin - 如何下载 .mp3 文件并保存到内部存储

Kotlin - How to download .mp3 file and save to Internal storage

我正在尝试从 url 下载 .mp3 文件并保存到内部存储器。我已经能够下载数据并保存,但音频文件听起来不正确。听起来一点也不像原版。

我可以 select View -> Tool Windows -> Device File Explorer 然后打开 data/data/[myPackageName]/files 并保存 audio.mp3 文件然后播放,但时间不正确,字节大小错误,音频听起来不正常

这是我的 AsyncTask class:

    class DownloadAudioFromUrl(val context: Context): AsyncTask<String, String, String>() {

        override fun doInBackground(vararg p0: String?): String {
            val url  = URL(p0[0])
            val connection = url.openConnection()
            connection.connect()
            val inputStream = BufferedInputStream(url.openStream())
            val filename = "audio.mp3"
            val outputStream = context.openFileOutput(filename, Context.MODE_PRIVATE)
            val data = ByteArray(1024)
            var total:Long = 0
            var count = 0
            while (inputStream.read(data) != -1) {
                count = inputStream.read(data)
                total += count
                outputStream.write(data, 0, count)
            }
            outputStream.flush()
            outputStream.close()
            inputStream.close()
            println("finished saving audio.mp3 to internal storage")
            return "Success"
        }

    }

然后在我的 activity onCreate() 我执行任务

        val urlString = "https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_5MG.mp3"
        DownloadAudioFromUrl(this).execute(urlString)

.

看起来你的 write 方法顺序错误,你每个循环进行两次读取,但只捕获其中一次

试试这个

var count = inputStream.read(data) 
var total = count 
while (count != -1) {
    outputStream.write(data, 0, count)
    count = inputStream.read(data)
    total += count
}