I am using MediaPlayer to play music from url when my activity start. It works well on API above 19 but not working on API 19 (emulator). Why is this happening and how to solve it?
I have searched this problem on stackoverflow, most of the answer suggest that the error is caused by bad connectivity or invalid state (media is being played before prepared), but I did use the prepareAsync
method and start the audio in onPrepared
method. I also did the test on other device and emulator (with API above 19) and there is no error occured.
This is my code.
private lateinit var mediaPlayer: MediaPlayer
private var isMediaPrepared: Boolean = false
private val backsoundUrl = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-8.mp3"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_game)
mediaPlayer = createPlayer()
mediaPlayer.apply {
try {
setDataSource(backsoundUrl)
isLooping = true
setOnPreparedListener { mp ->
isMediaPrepared = true
mp.start()
}
prepareAsync()
} catch (e: IllegalStateException) {
e.printStackTrace()
} catch (e: IllegalArgumentException){
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
private fun createPlayer(): MediaPlayer {
return MediaPlayer().apply {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
setAudioAttributes(
AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_MEDIA)
.build()
)
} else {
setAudioStreamType(AudioManager.STREAM_MUSIC)
}
}
}
override fun onStop() {
super.onStop()
if (mediaPlayer.isPlaying) {
mediaPlayer.pause()
}
}
override fun onDestroy() {
if (mediaPlayer.isPlaying) {
mediaPlayer.stop()
}
mediaPlayer.reset()
mediaPlayer.release()
super.onDestroy()
}
Edit: This is my logcat
01-20 10:15:52.248 5171-5171/com.example.guessthesound E/MediaPlayer: Should have subtitle controller already set
01-20 10:15:52.518 5171-5183/com.example.guessthesound E/MediaPlayer: error (1, -1004)
01-20 10:15:52.518 5171-5171/com.example.guessthesound E/MediaPlayer: Error (1,-1004)
Edit 2:
This code used to work on emulator API 21, but now it cannot play the audio and the logcat only show error E/MediaPlayer: Should have subtitle controller already set
. I read https://stackoverflow.com/a/20149754/11986468 and other similar questions, most of the answer suggest to just ignore it. I don't know if it cannot play the audio because of this error or not but there is no other error. After I found this, I tried to test on device with API 21 and it works well, so may be there's something wrong with the emulator? Is it possible the error on API 19 is because I was using emulator? (I am using Android Studio emulator)
What might be the caused and can this be fixed?