Kotlin-如何下载.mp3文件并将其保存到内部存储中 [英] Kotlin - How to download .mp3 file and save to Internal storage

查看:80
本文介绍了Kotlin-如何下载.mp3文件并将其保存到内部存储中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从URL下载.mp3文件并将其保存到内部存储中.我已经能够下载数据并将其保存,但是音频文件听起来不正确.听起来不像原始音乐.

I'm attempting to download a .mp3 file from a url and save to internal storage. I've been able to download the data and save it but the audio file does not sound correct. It doesn't sound anything like the original.

我可以选择 View->工具窗口->设备文件资源管理器然后打开数据/数据/[myPackageName]/文件并保存audio.mp3文件,然后播放它,但时间不正确,字节大小错误,音频也没有声音

I'm able to select View -> Tool Windows -> Device File Explorer then open data/data/[myPackageName]/files and save the audio.mp3 file then play it but the time isn't correct, the byte size is wrong, and the audio is nothing like it should sound

这是我的AsyncTask类:

Here's my 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"
        }

    }

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

Then in my activity onCreate() I execute the task

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

.

推荐答案

看起来您的write方法顺序错误,并且您在每个循环中进行了两次读取,但仅捕获了其中之一

Looks like your write method is in the wrong order, and you're doing two reads per loop, but only capturing one of them

尝试一下

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

这篇关于Kotlin-如何下载.mp3文件并将其保存到内部存储中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆