title: Kotlin - How to download .mp3 file and save to Internal storage
body: <p>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.</p>
  
  <p>I'm able to select 
  <code>View -&gt; Tool Windows -&gt; Device File Explorer</code>
  then open 
  <code>data/data/[myPackageName]/files</code>
   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</p>
  
  <p>Here's my AsyncTask class:</p>
  
  <pre><code>    class DownloadAudioFromUrl(val context: Context): AsyncTask&lt;String, String, String&gt;() {
  
          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"
          }
  
      }
  </code></pre>
  
  <p>Then in my activity 
  <code>onCreate()</code>
   I execute the task</p>
  
  <pre><code>        val urlString = "https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_5MG.mp3"
          DownloadAudioFromUrl(this).execute(urlString)
  </code></pre>
  
  <p>.</p>