【问题标题】:Kotlin - How to download .mp3 file and save to Internal storageKotlin - 如何下载 .mp3 文件并保存到内部存储
【发布时间】:2019-09-28 01:15:03
【问题描述】:

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

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

这是我的 AsyncTask 类:

    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"
        }

    }

然后在我的活动中 onCreate() 我执行任务

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

.

【问题讨论】:

    标签: android audio kotlin android-asynctask


    【解决方案1】:

    看起来您的写入方法顺序错误,每个循环执行两次读取,但只捕获其中一次

    试试这个

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

    【讨论】:

    • 完美!那解决了它。谢谢!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 2017-12-05
    • 2020-06-30
    • 2013-02-19
    相关资源
    最近更新 更多