Search code examples
androidkotlinmp3raw

Koltin, setting a mediaplayer from a variable


I'm working on an application, where for specific choosen items, specific .mp3 should be assigned. (Like I choose Dachshund, then I dachshund_1.mp3, dachshund_2.mp3 etc. to be played when my functions say so). Is it possible somehow, that I create a variable, that holds the specific name, then I assign it to mediaplayer.create?

What I would like to do would look like that below:

// I have a function here that returns with the specific string
// I have a cnt variable in the code which helps determine which text and sound comes now
fun DogHandler(cnt:Int, receiptName: String) :String
{
   return dogName + "_" +cnt.toString()
}

This function is called, and the string it returns should go to the mediaplayer. Cnt is let's say 10

var tmp = DogHandler(dachshund, cnt);     // tmp = dachsund_10
mediaPlayer = MediaPlayer.create(context, R.raw.tmp)
mediaPlayer.start()

Solution

  • To my knowledge there is no way to generate resource IDs (like R.raw.something) dynamically. However, you could simply create a list of them and access it by index.

    val dachsunds = listOf(
        R.raw.dachsund_0,
        R.raw.dachsund_1,
        R.raw.dachsund_2,
        R.raw.dachsund_3,
        // ...
        R.raw.dachsund_10
    )
    
    val dachsund = dachsunds[dachsundIndex]
    val mediaPlayer = MediaPlayer.create(context, dachsund).apply {
        start()
    }