简体   繁体   中英

How to play a different sound file from res>raw

Under class I have

private lateinit var mp: MediaPlayer

Under override I have

mp = MediaPlayer.create(this, R.raw.a1)

Function buttonPlayClick which is also buttonPlay

fun buttonPlayClick(v: View)
{
    if (mp.isPlaying)
    {
        mp.pause()
        buttonPlay.text = "PLAY"

} else {
    mp.start()
        buttonPlay.text = "PAUSE"
    }
}

I am using the code below to point to a sound file

mp = MediaPlayer.create(this, R.raw.a1)

Currently, the command is pointing to a sound file called a1 in res>raw

I am learning Kotlin bit by bit and I am trying to play a different sound file using the command below (changed a1 to x)

mp = MediaPlayer.create(this, R.raw.x)

I was hoping that at some point in the app I can define x = a1 or a2 or a3 to play different sounds files but it does not work like that. I also noticed that the sound files cannot just be an integer value. The sound files are very short (3 to 10 seconds)

Thanks for all the help!

You can do something like this :

var a1 = R.raw.a1
var a2 = R.raw.a2
var a3 = R.raw.a3

Or you can do it with JAVA like this :

int setMusic(String mMusic){
  return this.getResources().getIdentifier(mMusic, "raw", this.getPackageName());
}

and call it like this :

mp = MediaPlayer.create(this, setMusic("a1"))

or

mp = MediaPlayer.create(this, setMusic("a2"))

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