1

I want to play some raw audio files from a media player. But in my fragment, I only have access to the name of the file, i.e. "yeet".

Can I generate the resource file from the name alone, and then pass it to the media player?

var resFileName: String? = null
for (it in mItemList) {
    val resName = mItemList.find { it.first == uniqueId }?.second
    resFileName = "R.raw.$resName"
}

// Get raw resource from name and play sound
val raw = view!!.context.assets.open("$resFileName.mp3")
mp = MediaPlayer.create(view!!.context, raw) // This doesn't work; requires URI! or Int

Edit: Can we re-open this to address Kotlin syntax?

My Answer:

val raw = view!!.context.resources.getIdentifier("$resFileName",
        "raw", view.context.packageName)
println("Resource Name: $raw")

mp!!.reset()
mp = MediaPlayer.create(view.context, raw)
mp!!.start()
Martin Erlic
  • 5,467
  • 22
  • 81
  • 153

0 Answers0