How to adjust volume during audio playback using MediaPlayer in Kotlin Android
How to adjust volume during audio playback using MediaPlayer in Kotlin Android.
Here's a step-by-step tutorial on how to adjust volume during audio playback using MediaPlayer in Kotlin for Android.
Step 1: Set up the project
- Create a new Android project in Android Studio.
- Add the necessary permissions in the AndroidManifest.xml file to access audio settings:
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
Step 2: Add MediaPlayer to the project
- In the app-level build.gradle file, add the MediaPlayer dependency:
implementation 'androidx.media:media:1.4.3'
Step 3: Initialize the MediaPlayer
- Create an instance of MediaPlayer in your activity or fragment:
private lateinit var mediaPlayer: MediaPlayer
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mediaPlayer = MediaPlayer()
}
Step 4: Prepare the audio file
- Place the audio file you want to play in the res/raw directory.
- Prepare the audio file for playback:
mediaPlayer.setDataSource(applicationContext, Uri.parse("android.resource://$packageName/${R.raw.audio_file}"))
mediaPlayer.prepare()
Step 5: Adjust the volume
- To adjust the volume during audio playback, you can use the setVolume method of the MediaPlayer class. The method takes two parameters: leftVolume and rightVolume, both ranging from 0.0 to 1.0.
- For example, to set the volume to half of the maximum:
mediaPlayer.setVolume(0.5f, 0.5f)
Step 6: Control volume using SeekBar
- Add a SeekBar widget to your layout file (activity_main.xml) to control the volume:
<SeekBar
android:id="@+id/volumeSeekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="50" />
- In your activity or fragment, initialize the SeekBar and set a listener to update the volume:
private lateinit var volumeSeekBar: SeekBar
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mediaPlayer = MediaPlayer()
volumeSeekBar = findViewById(R.id.volumeSeekBar)
volumeSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
val volume = progress / 100f
mediaPlayer.setVolume(volume, volume)
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {}
override fun onStopTrackingTouch(seekBar: SeekBar?) {}
})
}
Step 7: Play and stop audio
- Implement the play and stop functionality using buttons or other UI elements:
fun playAudio() {
mediaPlayer.start()
}
fun stopAudio() {
mediaPlayer.stop()
mediaPlayer.prepare()
}
That's it! You now have a functioning audio playback system with volume control using MediaPlayer in Kotlin for Android.