Search code examples
androidaudiokotlinandroid-asynctask

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


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.

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

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

    }

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)

.


Solution

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

    Try this

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