Home > Enterprise >  Is there a way to access the files of res/raw dynamically via MediaPlayer.create() instead of settin
Is there a way to access the files of res/raw dynamically via MediaPlayer.create() instead of settin

Time:03-16

I am trying to build a simple soundboard.

Following situation:

  • I already added the 'kotlin-android-extensions' to the build.gradle file
  • Filled the activity_main.xml with buttons
  • All buttons use the same method: fun playSound()
  • All buttons are tagged (I use the tag in order to access the files in raw via passed view.getTag())

The problem is that I can't find a way to access the res/raw-files "dynamically", because the MediaPlayer.create() requires a static path to the file (e.g. "R.raw.filename").

The code should look something like this but the .create does not accept a variable (the variable "path") but instead asks for the static path (e.g. "R.raw.filename").

fun playSound(view: View) {
        var path: String = "R.raw."   view.getTag()
        mediaPlayer = MediaPlayer.create(applicationContext, path)
        mediaPlayer.start()
}

I tried to solve the problem with the "resid" (the integer that is assigned to the files when they are put into the res/raw folder) but that did not work (the app always crashed). I searched a lot but the only solutions I found did not help me and I no longer know what to look for or whether the problem can be solved at all.

Thanks in advance!

CodePudding user response:

You can find the Resource Id by name from raw folder using the resources.getIdentifier() which can be used in MediaPlayer.create(applicationContext, resId) something like the below:

fun playSound(view: View) {
    val fileNameWithoutExtension: String = view.getTag() as String
    val resId = resources.getIdentifier(fileNameWithoutExtension, "raw", packageName)
    if (resId != 0) {
        val mediaPlayer = MediaPlayer.create(applicationContext, resId)
        mediaPlayer.start()
    }
}

Make sure that the filename you are passing using the view.getTag() doesn't contains the file extension.

  • Related