Reputation: 41
How do I pass a filename parameter to MediaPlayer in android kotlin?
I have a sound file called "hello.wav" which is in the res/raw directory. I have tried the following code and it will not accept the parameter sndfil as there is no file called sndfil.wav in the res/raw directory...
private var sndfil = "xxxxxxxxxx"
fun playnow (sndfil: String) {
mp = MediaPlayer.create(this, R.raw.sndfil)
mp.start()
return
}
playnow("hello")
How can a filename be passed as a parameter to android MediaPlayer ?
Upvotes: 2
Views: 350
Reputation: 2515
take a look at the getIdentifier
method it returns a resource identifier for the given resource name.
fun playnow (sndfil: String) {
val resourceIdentifier = resources.getIdentifier(sndfil, "raw", packageName)
mp = MediaPlayer.create(this,resourceIdentifier)
mp.start()
return
}
playnow("hello")
Upvotes: 1