Home > Net >  Jetpack compose play remote audio through URL
Jetpack compose play remote audio through URL

Time:10-04

I have been able to use MediaPlayer to play a local file in drawable but could not figure out how to play a remote file. Could not find relevant info from the internet too.

Below is what I have come out but it doesn't work. Any help would be greatly appreciated.

@Composable
fun MainScreen() {
    val context = LocalContext.current
    val url = "https://www.learningcontainer.com/wp-content/uploads/2020/02/Kalimba.mp3"
    Button(onClick = {
        val mediaPlayer = MediaPlayer()
        mediaPlayer.setAudioAttributes(
            AudioAttributes.Builder()
                .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                .build()
        )

        try {
            mediaPlayer.setDataSource(context, Uri.parse(url))
            mediaPlayer.prepare()
            mediaPlayer.start()
        } catch (e: IOException) {
            e.printStackTrace()
        }

    }) {
        Text(text = "Play")
    }
}

CodePudding user response:

I tried the above code and it works fine for me. Try again with a different device or restart the emulator (if you are testing on an emulator).

One optimisation that you can do here is to replace prepare with prepareAsync. prepare will block the UI thread. Fetching audio from Internet takes some time and UI will remain unresponsive till then. prepareAsync, on the other hand, does the preparation on a background thread.

mediaPlayer.prepareAsync()
mediaPlayer.setOnPreparedListener { mp ->
    mp.start()
}
  • Related