简体   繁体   中英

How to set a new audio data source for Android MediaPlayer in Kotlin

New to Android and Kotlin...

I am trying to set a new audio data source for the Android MediaPlayer. The below code compiles and runs, but the sound isn't played. No crash, no errors. The toast "Media Player prepared!" never shows up, so I think the media player does not get prepared.

If I comment out the lines following "val mediaPlayer = MediaPlayer.create(this, R.raw.fifo50)", then it plays the fifo50 sound when I click the btnMaintain button.

What is missing here?

class MainActivity :
AppCompatActivity(),
MediaPlayer.OnPreparedListener{


override fun onCreate(savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val btnMaintain = findViewById<Button>(R.id.btnMaintain)
    val mediaPlayer = MediaPlayer.create(this, R.raw.fifo50)
    mediaPlayer.stop()
    mediaPlayer.reset()
    mediaPlayer.setAudioAttributes(
        AudioAttributes.Builder()
            .setUsage(AudioAttributes.USAGE_MEDIA)
            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
            .build()
                )
    mediaPlayer.setDataSource("android.resource://" + this.packageName + "/raw/maintain_speed")
    Toast.makeText(this, "Preparing Media Player", Toast.LENGTH_SHORT).show()
    mediaPlayer.setOnPreparedListener(this)
    mediaPlayer.prepareAsync()
    Toast.makeText(this, "Asynchronous preparation of Media Player started", Toast.LENGTH_SHORT).show()

    btnMaintain.setOnClickListener() {
        mediaPlayer.isLooping = true
        mediaPlayer.start()
    }
}

override fun onPrepared(p0: MediaPlayer) {
    Toast.makeText(this, "Media Player prepared!", Toast.LENGTH_SHORT).show()
}

}

MediaPlayer.create(...) return new instance of MediaPlayer after call prepare() . Is useless to call stop() and reset() after create(...) . Using raw resource you have to setDataSource with AssetFileDescriptor like setDataSource(resources.openRawResourceFd(R.raw.your_media))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM