Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android get R.raw from variable

Tags:

android

i have some sounds in a raw folder on my app. And sometimes i need to play a sound, but i don't know exactly which is.

Example :

String actualSound = "hit"

playSound(mediaPlayer, R.Raw.actualSound));

I want to play the R.raw.hit but i don't know how to do that.

like image 573
Dahevos Avatar asked Aug 24 '11 21:08

Dahevos


1 Answers

You can obtain the numeric ID of your raw resource using Resources.getIdentifier() and then use it in your play function:

Resources res = context.getResources();
int soundId = res.getIdentifier(actualSound, "raw", context.getPackageName());
playSound(mediaPlayer, soundId);

Note that generally, you shouldn't do this. It is more efficient to access resources by numeric identifier (i.e. R-qualified constant). This would especially matter if you were to do the above every time you want to play sound in a game. It is better to use a mapping of sound names (or better yet: enum values) to resource identifiers or even pre-loaded sound samples.

like image 88
Xion Avatar answered Oct 07 '22 00:10

Xion