Reputation: 8685
I have the following code to play audio in android. I'm using Kotlin. How can I make sure the audio plays in the background once the app is closed?
// Start the media player
playBtn.setOnClickListener {
if (pause && mediaPlayer.isPlaying) {
playBtn.setImageResource(R.drawable.ic_play_circle_filled);
mediaPlayer.pause()
} else {
playBtn.setImageResource(R.drawable.pausebtn);
if (pause) {
mediaPlayer.seekTo(mediaPlayer.currentPosition)
mediaPlayer.start()
} else {
mediaPlayer = MediaPlayer.create(applicationContext, Uri.parse(intent.getStringExtra("audio")))
mediaPlayer.start()
}
initializeSeekBar()
mediaPlayer.setOnCompletionListener {
Toast.makeText(this, "end", Toast.LENGTH_SHORT).show()
}
}
pause = !pause;
}
prevBtn.setOnClickListener {
try {
mediaPlayer.seekTo(mediaPlayer.currentPosition + (-10*1000))
} catch(e: UninitializedPropertyAccessException) {
// media player is not initialized
}
}
nextBtn.setOnClickListener {
try {
mediaPlayer.seekTo(mediaPlayer.currentPosition + (10*1000))
} catch(e: UninitializedPropertyAccessException) {
// media player is not initialized
}
}
// Seek bar change listener
seek_bar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) {
if (b) {
try {
mediaPlayer.seekTo(i * 1000)
} catch(e: UninitializedPropertyAccessException) {
// media player is not initialized
}
}
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
}
})
Upvotes: 0
Views: 1935
Reputation: 707
For making the music to play in the background, you should implement the MediaPlayer API as a Service. Here is step by step guide on how you can implement the same - building a media player app
This example is in Java, hope you can understand and interpret in kotlin, else use the built in java to Kotlin converter in Android studio.
Upvotes: 3