0

In the raw directory I have files named rhode1.mp3 to rhode49.mp3.

I need to randomly play one of these files so I'm randomly generating a number and attaching it to R.raw.rhode to use as URI (uri1 in the code below), but it crashes the app. When I replace uri1 with R.raw.rhode1 for example it works and the audio file plays.

I tried writing R.raw.rhode$note1.mp3 and it still didn't work. Also tried:

("R.raw.rhode" + note1.toString() + ".mp3")

And:

("R.raw.rhode" + note1.toString())

override fun onCreate (savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    var mediaplayer: MediaPlayer? = null
    val letsgo = findViewById<Button>(R.id.start)
    val think = findViewById<SeekBar>(R.id.think)
    val extime = findViewById<SeekBar>(R.id.extime)
    val rpt = findViewById<SeekBar>(R.id.rpt)
    val rtime = findViewById<SeekBar>(R.id.rtime)
    var note1: Int
    var uri1: Uri

    letsgo.setOnClickListener {

        note1 = Random.nextInt(49) + 1
        uri1 = Uri.parse("R.raw.rhode" + note1.toString())
        mediaplayer = MediaPlayer.create(applicationContext, uri1)
        mediaplayer!!.start()
    }
}
double-beep
  • 5,031
  • 17
  • 33
  • 41
  • Possible duplicate of [Unfortunately MyApp has stopped. How can I solve this?](https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this) – double-beep Jun 14 '19 at 19:43

1 Answers1

0

R.resourceType.resourceName is a valid symbol from the point of the programming language. But it is, obviously, not an URL/URI.

Here is a sample of how to construct a resource URI: https://stackoverflow.com/a/7979084/3050249

Miha_x64
  • 5,973
  • 1
  • 41
  • 63
  • Tried to fix this for 3h yesterday (in vain). Thank you so much. For people with the same problem, fix: uri1 = Uri.parse("android.resource://" + getPackageName() + "/raw/rhode" + note1.toString()) for some reason this: uri1 = Uri.parse("android.resource://" + getPackageName() + "/R.raw.rhode" + note1.toString()) which was also proposed in that link did not work. – André Gonçalves Jun 13 '19 at 11:32