Android Jetpack Compose - Manage Audio Focus

Last Updated : 23 Jul, 2025

Audio focus is important to manage while building an application that plays an audio file within the application. With the help of this, we can again play the audio file from where it was paused originally. In this article, we will take a look at How to manage audio focus in android applications using Jetpack Compose.

Steps to Implement Manage Audio Focus

Step 1: Create a New Project in Android Studio

To create a new project in the Android Studio, please refer to How to Create a new Project in Android Studio with Jetpack Compose.

Step 2: Add a music file to raw folder

Navigate to app > res, now right click on the res folder and select New > Android resource directory, specify name and type as raw and select Ok. Now, right click on the raw folder and paste your music file.

Step 3: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

MainActivity.kt:

Kotlin
package com.geeksforgeeks.demo

import android.media.AudioAttributes
import android.media.AudioFocusRequest
import android.media.AudioManager
import android.media.AudioManager.OnAudioFocusChangeListener
import android.media.MediaPlayer
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.annotation.RequiresApi
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import com.geeksforgeeks.demo.ui.theme.DemoTheme
import java.io.IOException

class MainActivity : ComponentActivity() {

    private var mediaPlayer: MediaPlayer? = null
    private var audioManager: AudioManager? = null
    private var playbackAttributes: AudioAttributes? = null
    private var audioFocusChangeListener =
        OnAudioFocusChangeListener { focusChange ->
            when (focusChange) {
                AudioManager.AUDIOFOCUS_GAIN -> mediaPlayer!!.start()
                AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> {
                    mediaPlayer!!.pause()
                    mediaPlayer!!.seekTo(0)
                }

                AudioManager.AUDIOFOCUS_LOSS -> {
                    mediaPlayer!!.release()
                }
            }
        }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // get the audio system service
        // for the audioManager instance
        audioManager = getSystemService(AUDIO_SERVICE) as AudioManager

        // initiate the audio playback attributes
        playbackAttributes = AudioAttributes.Builder()
            .setUsage(AudioAttributes.USAGE_GAME)
            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
            .build()

        // set the playback attributes
        // for the focus requester
        val focusRequest = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
            .setAudioAttributes(playbackAttributes!!)
            .setAcceptsDelayedFocusGain(true)
            .setOnAudioFocusChangeListener(audioFocusChangeListener)
            .build()

        // request the audio focus and
        // store it in the int variable
        val audioFocusRequest = audioManager!!.requestAudioFocus(focusRequest)

        // initiate the media player instance
        // with the media file from the raw folder
        mediaPlayer = MediaPlayer.create(applicationContext, R.raw.sample);


        setContent {
            DemoTheme {
                AudioController(mediaPlayer, audioFocusRequest)
            }
        }
    }
}

@Composable
fun AudioController(
    mediaPlayer: MediaPlayer?,
    audioFocusRequest: Int
) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(all = 30.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center,
    ) {
    
        // Stop button
        Button(onClick = {
            mediaPlayer!!.stop()

            try {
            
                // if the media-player is stopped then
                // it should be again prepared for
                // next instance of play
                mediaPlayer.prepare()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }, modifier = Modifier.width(300.dp)) {
            Text(text = "Stop", color = Color.White)
        }

        Spacer(modifier = Modifier.height(10.dp))

        // Pause button
        Button(onClick = {
            mediaPlayer!!.pause()
        }, modifier = Modifier.width(300.dp)) {
            Text(text = "Pause", color = Color.White)
        }

        Spacer(modifier = Modifier.height(10.dp))

        // Play button
        Button(onClick = {
        
            // start media player.
            if (audioFocusRequest == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                mediaPlayer!!.start();
            }
        }, modifier = Modifier.width(300.dp)) {
            Text(text = "Play", color = Color.White)
        }

    }
}

Output:

Comment

Explore