skip to Main Content

I have an mp3 file for every word in my adapter so I want MediaPlayer to create a new sound based on the index of the RecyclerView

To demonstrate what I want:

if 0th index of the RecyclerView is Mother,
mp = MediaPlayer.create(holder.itemView.context, R.raw.mother)

if 1st index of the RecyclerView is Father,
mp = MediaPlayer.create(holder.itemView.context, R.raw.father)

To solve this I tried:

 override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = items[position]

        holder.vocabularyItem.text = item.vocab
        holder.vocabularyTranslation.text = item.Translation

        mp = MediaPlayer.create(holder.itemView.context, R.raw.${item.vocab})
        mp.setVolume(0.5f, 0.5f)


        holder.symbol.setOnClickListener {
            mp.start()
        }
    }

but this part gives an error:
mp = MediaPlayer.create(holder.itemView.context, R.raw.${item.vocab})

How can I access a file in R.raw with a variable?

EDIT:

As recommended, I changed the relevant code with:

mp = MediaPlayer.create(holder.itemView.context, holder.itemView.context.resources.getIdentifier(item.vocab.toLowerCase(), "raw", holder.itemView.context.packageName))

The code works now but it only says the last element of the recyclerView.

When clicked on the 0th index, mother, it says "father"
When clicked on the 1st index, father, it says "father" again

I checked whether something wrong with recyclerView or not in the following code:

holder.vocabularyItem.setOnClickListener {
            Toast.makeText(holder.itemView.context, "hello you just clicked on: ${item.vocab.toLowerCase()}", Toast.LENGTH_SHORT).show()
        }

Toast message shows "Mother" and "Father" respectively which shows the recyclerView works fine. Does anyone have any idea what is wrong with the section starting with mp ?

2

Answers


  1. two solutions I could think of:

    1. create a map to store the vocab to raw resource mapping.
    2. create Kotlin extension function to convert a resource name to resource Id conveniently. see How to get a resource id with a known resource name?
    Login or Signup to reply.
  2. The problem in your edit is caused by how you do the mp.create and mp.play. You have a single MediaPlayer variable that stores the value in onBind. That means that the player will be for the file in the last call of onBind. You need to create and play the media player in the button handler, or you need to create it once when this adapter is created but change the source in the click handler. Preferably the second solution, as creating a media player isn’t cheap.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search