views:

104

answers:

1

I think I should know this, but my mind has gone blank. I'm making an app that has a few hundred small sound files and I want it to play a certain file dependent on a String I pass to the function. Where I hit the brick wall is getting the resId of the sound file.

I am using this code:

MediaPlayer mp = MediaPlayer.create(context, R.raw.sound_file_1);
mp.start();

Gotten from here: http://developer.android.com/guide/topics/media/index.html

All I need is some help passing in a variable resId. Can anyone give me a hand?

+1  A: 

Use getResources().getIdentifier() to convert the String into a resource ID. Please cache the result, as this lookup is done using reflection and therefore is a bit expensive in terms of CPU.

CommonsWare
Thanks for the reply. I have been trying to use this method (unsure of whether or not it was right). Thanks for pointing me in the right direction.Do you know how I can access the Res folder? I've tried with and without package names but I have had no luck. Thanks again
TehGoose
@TehGoose: I do not know what you mean by "access the Res folder", sorry.
CommonsWare
Thank you. I have gotten it using the method you said. The problem was that I had stored my audio file in R.raw, and I couldn't seem to use the file while it's there. I was just using the method wrong. Thanks
TehGoose