Mauker
Mauker

Reputation: 11487

MediaPlayer crashes on setDataSource with R.raw audio

I'm making an Audio Player app that will load some predefined audios from inside its raw resource folder.

I've sent the test APK for some people to test it, and it worked on 99% of the cases. But then, I started to get some crash reports on Crashlytics for a single device, the OnePlus A5000, running Android 8.1.0.

The stacktrace on crashlytics is as follows:

Fatal Exception: java.lang.IllegalStateException
       at android.media.MediaPlayer._setDataSource(MediaPlayer.java)
       at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1270)
       at com.example.home.MediaPlayerHolder.loadMedia(MediaPlayerHolder.kt:56)
       at com.example.home.HomePresenter.playSound(HomePresenter.kt:26)
       at com.example.home.HomeFragment.onPlaySelected(HomeFragment.kt:178)
       at com.example.home.SoundItemAdapter$ViewHolder$bind$1.onClick(SoundItemAdapter.kt:30)

package names were changed for privacy reasons

This is happening almost every time he clicks on the sound item play button. It also happens on the first time he clicks on any sound item.

I've tried to reproduce this crash on some devices, all of then have API <= 25, but I had no success doing so. All of them ran without an issue. I'm clueless of the probable cause of this error, or even if it's an edge case problem, or if there's indeed something wrong with my code.

This is how I'm loading the audio on the MediaPlayer:

if (mediaPlayer?.isPlaying == true) {
    mediaPlayer?.release()
    mediaPlayer = null
}
if (mediaPlayer == null) {
    mediaPlayer = MediaPlayer()
}

val fileDescriptor = context.resources.openRawResourceFd(resource)
mediaPlayer?.setDataSource(fileDescriptor.fileDescriptor, fileDescriptor.startOffset, fileDescriptor.length)
fileDescriptor.close()
mediaPlayer?.prepare()
mediaPlayer?.start()

Upvotes: 2

Views: 655

Answers (1)

Sheikh Hasib
Sheikh Hasib

Reputation: 7493

The reason was you can't start services in the background anymore after API 26. So you have to start ForegroundService above API 26.

Upvotes: 1

Related Questions