5

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.

jalsh
  • 718
  • 5
  • 16
Dahevos
  • 1,465
  • 4
  • 16
  • 26

2 Answers2

15

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.

Xion
  • 20,785
  • 9
  • 48
  • 77
1

Quick answer:

public class WebsiteActivity extends AppCompatActivity {

    MediaPlayer mediaPlayer;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_website);

        Resources res = getResources();
        int sound = res.getIdentifier(music, "raw", getPackageName());

        //Play music
        mediaPlayer = MediaPlayer.create(getApplicationContext(), sound);
        mediaPlayer.start();
    }

    @Override
    protected void onPause() {
        super.onPause();

        mediaPlayer.stop();
        mediaPlayer.reset();
    }
}
myworldbox
  • 118
  • 1
  • 10