How to show AudioPlayer in Jetpack Compose - Android Media Player to play music

Last updated Oct 26, 2021


In this Jetpack compose tutorial we will learn how to show audio player using Jetpack compose in Android application. To play any music we need to a music player, so how we will create music player with jetpack compose, by using android MediaPlayer  we will create audio player then play the audio by passing its URL to media player.

 

Let's get started

Step 1: Create android application in android studio

Step 2: Follow step for setup Jetpack Compose with Android Studio

To show/play audio player we are going to use MediaPlayer  Api which is used to for playing different types of media such audio,video etc.

Lets add button from which we are going to select audio from mobile

Scaffold(content = {
    Column(modifier = Modifier
        .fillMaxWidth()
        .fillMaxHeight()
        .padding(16.dp), content = {
        Button(onClick = {
        }) {
            Text(text = "Click to Select Audio")
        }
    })
}, topBar = {
    TopAppBar(
        backgroundColor = Color.White,
        title = { Text("Audio Player Demo") },
        modifier = Modifier
            .padding(horizontal = 16.dp, vertical = 8.dp), elevation = 10.dp
    )
})

 

 

On clicking button lets select an audio

val audioData = remember { mutableStateOf(null) }
val launcher =
    rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) {
        audioData.value = it
    }

 

 

Button(onClick = {
    launcher.launch(
        "audio/*"
    )
}) {
    Text(text = "Click to Select Audio")
}

 

 

Ui for showing audio after selection

audioData.let {
    val uri = it.value
    if (uri != null) {
        Row(
            content = {
                Card(content = {
                    Icon(
                        imageVector = Icons.Default.SettingsVoice,
                        contentDescription = "image",
                        tint = Color.Red, modifier = Modifier.padding(16.dp)
                    )
                }, shape = RoundedCornerShape(16.dp))
                Column(content = {
                    Text(
                        text = "Audio",
                        fontSize = 20.sp,
                        modifier = Modifier.padding(start = 16.dp),
                        fontWeight = FontWeight.Bold
                    )
                    Text(
                        text = fetchFormattedDate(
                            Calendar.getInstance().time,
                            "dd MMM, yyyy | hh:mm:ss a"
                        ),
                        fontSize = 16.sp,
                        color = Color.LightGray,
                        modifier = Modifier.padding(start = 16.dp, top = 4.dp)
                    )
                })
            }, modifier = Modifier
                .fillMaxWidth()
                .padding(top = 16.dp, start = 16.dp, end = 16.dp)
        )
        val player = MediaPlayer.create(context, uri)
        ShowAudioSlider(player = player)
    } else {
        Button(onClick = {
            launcher.launch(
                "audio/*"
            )
        }) {
            Text(text = "Click to Select Audio")
        }
    }

}

 

 

Now lets add ui for slider and play button

@Composable
fun ShowAudioSlider(player: MediaPlayer?) {
    val playing = remember {
        mutableStateOf(false)
    }
    val position = remember {
        mutableStateOf(0F)
    }
    if (player != null) {
        Slider(
            value = position.value,
            valueRange = 0F..player.duration.toFloat(),
            onValueChange = {
                position.value = it
                player.seekTo(it.toInt())
            }
        )
        Icon(
            imageVector = if (!playing.value || player.currentPosition == player.duration) Icons.Default.PlayCircleOutline else Icons.Default.PauseCircleOutline,
            contentDescription = "image",
            tint = Color.Red, modifier = Modifier
                .padding(16.dp)
                .size(20.dp)
                .clickable(onClick = {
                    if (player.isPlaying) {
                        player.pause()
                        playing.value = false
                    } else {
                        player.start()
                        playing.value = true
                    }

                    object : CountDownTimer(player.duration.toLong(), 100) {

                        override fun onTick(millisUntilFinished: Long) {
                            position.value = player.currentPosition.toFloat()
                            if (player.currentPosition == player.duration) {
                                playing.value = false
                            }
                        }

                        override fun onFinish() {

                        }
                    }.start()
                })
        )
    }

}

 

Complete example code for Android audio player with jetpack compose

package com.example.jetpack

import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import android.os.CountDownTimer
import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PauseCircleOutline
import androidx.compose.material.icons.filled.PlayCircleOutline
import androidx.compose.material.icons.filled.SettingsVoice
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.jetpack.widget.fetchFormattedDate
import java.util.*

class MainActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
        setContent {
            AudioPlayerDemo()
        }
    }
}

@Composable
fun AudioPlayerDemo() {
    val context = LocalContext.current
    val audioData = remember { mutableStateOf(null) }
    val launcher =
        rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) {
            audioData.value = it
        }
    Scaffold(content = {
        Column(modifier = Modifier
            .fillMaxWidth()
            .fillMaxHeight()
            .padding(16.dp), content = {
            audioData.let {
                val uri = it.value
                if (uri != null) {
                    Row(
                        content = {
                            Card(content = {
                                Icon(
                                    imageVector = Icons.Default.SettingsVoice,
                                    contentDescription = "image",
                                    tint = Color.Red, modifier = Modifier.padding(16.dp)
                                )
                            }, shape = RoundedCornerShape(16.dp))
                            Column(content = {
                                Text(
                                    text = "Audio",
                                    fontSize = 20.sp,
                                    modifier = Modifier.padding(start = 16.dp),
                                    fontWeight = FontWeight.Bold
                                )
                                Text(
                                    text = fetchFormattedDate(
                                        Calendar.getInstance().time,
                                        "dd MMM, yyyy | hh:mm:ss a"
                                    ),
                                    fontSize = 16.sp,
                                    color = Color.LightGray,
                                    modifier = Modifier.padding(start = 16.dp, top = 4.dp)
                                )
                            })
                        }, modifier = Modifier
                            .fillMaxWidth()
                            .padding(top = 16.dp, start = 16.dp, end = 16.dp)
                    )
                    val player = MediaPlayer.create(context, uri)
                    A(player = player)
                } else {
                    Button(onClick = {
                        launcher.launch(
                            "audio/*"
                        )
                    }) {
                        Text(text = "Click to Select Audio")
                    }
                }

            }
        })
    }, topBar = {
        TopAppBar(
            backgroundColor = Color.White,
            title = { Text("Audio Player Demo") },
            modifier = Modifier
                .padding(horizontal = 16.dp, vertical = 8.dp), elevation = 10.dp
        )
    })
}

@Composable
fun A(player: MediaPlayer?) {
    val playing = remember {
        mutableStateOf(false)
    }
    val position = remember {
        mutableStateOf(0F)
    }
    if (player != null) {
        Slider(
            value = position.value,
            valueRange = 0F..player.duration.toFloat(),
            onValueChange = {
                position.value = it
                player.seekTo(it.toInt())
            }
        )
        Icon(
            imageVector = if (!playing.value || player.currentPosition==player.duration) Icons.Default.PlayCircleOutline else Icons.Default.PauseCircleOutline,
            contentDescription = "image",
            tint = Color.Red, modifier = Modifier
                .padding(16.dp)
                .size(20.dp)
                .clickable(onClick = {
                    if (player.isPlaying) {
                        player.pause()
                        playing.value = false
                    } else {
                        player.start()
                        playing.value = true
                    }

                    object : CountDownTimer(player.duration.toLong(), 100) {

                        override fun onTick(millisUntilFinished: Long) {
                            position.value = player.currentPosition.toFloat()
                            if (player.currentPosition == player.duration) {
                                playing.value = false
                            }
                        }

                        override fun onFinish() {

                        }
                    }.start()
                })
        )
    }

}


@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    AudioPlayerDemo()
}

 

Image

Jetpack Compose Audio player

Conclusion: In this jetpack compose tutorial we covered how to play audio files in android by show audio controllers with audio player.

 


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

134 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions