Search code examples
androidkotlinandroid-music-player

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!


Solution

  • 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"))