How should I download an audio file from a URL to downloads file? (What is the correct and Proper way?)

Viewed 100

I am trying to download an audio file from a URL. Though I have made it work with the following code:

val url = URL(getAudioFile(videoID)?.get(0)?.url) // Custom function
val connection = url.openConnection()
connection.connect()
val input = BufferedInputStream(url.openStream())
val output = context.openFileOutput("${filename}.mp3", Context.MODE_PRIVATE)
val data = ByteArray(1024)
var total: Long = 0
while (input.read(data).also { count = it } != -1) {
    total += count.toLong()
    output.write(data, 0, count)
}
output.flush()
output.close()
input.close()

However, this only downloads the file in the internal storage of the app. I want the audio file to be downloaded in the Downloads folder so it is more accessible.

I have tried using val output = FileOutputStream(pathway) but it doesn't quite work.

Also, other StackOverflow questions suggested using DownloadManager but I don't want to as it is deprecated.

There were some other solutions including downloading the file in the app, then copying it. I personally thought that it was extra computing time as well as manually needing to delete the files later so I did not try the method. (If this is the correct route then I'm sorry)

Is there any 2021 up-to-date solution to this that involves an audio file being downloaded directly to the Downloads folder? (Even better if it is a method that allows me to edit the metatags.)

0 Answers
Related