E. Williams
E. Williams

Reputation: 425

Android app freezes when creating MediaPlayer object

I want to create a MediaPlayer object to play a sound when an event is fired. So I moved a wav sound to res/raw directory and did this to create the object:

this.beep = MediaPlayer.create(applicationContext, R.raw.beep)

This compiles and the application runs normally, but when I open the activity where that line is typed, the screen becomes black. After running the debugger I can notice that no code is executed after that line is run.

Edit: this only happens on my physical device,on emulator it's ok.

Upvotes: 0

Views: 280

Answers (1)

Rahul Mishra
Rahul Mishra

Reputation: 1559

You can use MediaPlaer like this

private fun initMediaPlayer() {
    if (mediaPlayer == null) {
        // The volume on STREAM_SYSTEM is not adjustable, and users found it
        // too loud,
        // so we now play on the music stream.
        volumeControlStream = AudioManager.STREAM_MUSIC
        mediaPlayer = MediaPlayer()
        mediaPlayer!!.setAudioStreamType(AudioManager.STREAM_MUSIC)
        mediaPlayer!!.setOnCompletionListener(beepListener)
        val file: AssetFileDescriptor =
            resources.openRawResourceFd(R.raw.beep) as AssetFileDescriptor
        try {
            mediaPlayer!!.setDataSource(
                file.fileDescriptor,
                file.startOffset, file.length
            )
            file.close()
            mediaPlayer!!.setVolume(BEEP_VOLUME, BEEP_VOLUME)
            mediaPlayer!!.prepare()

        } catch (e: IOException) {
            mediaPlayer = null
        }
    }
}

And when you want to play media player call

mediaPlayer?.start()

And here is the beepListener

private val beepListener =
    OnCompletionListener { mediaPlayer ->
        mediaPlayer.seekTo(0)
    }

And don't forget to stop it at onPause()

mediaPlayer?.let { if (it.isPlaying) it.stop() }

Upvotes: 3

Related Questions