Search code examples
androidvariablesaudiomedia-player

Can I use a variable instead of the mp3 resource id to play a sound in android


I was wondering how I could replace the mp3name parameter with a variable that matches the MP3 name in the raw file. I have a number of mp3 files to call at various times but only really want to have one MediaPlayer method. Using a String variable does not seem to work as I get the error that the String variable name does not match a raw file.

Eg This does not work when there is an audiofile.mp3 in the raw file.

String playsound

playsound = audiofile

MediaPlayer mp = MediaPlayer.create(this, R.playsound);

How do I utilise a variable to get this to work? Thanks


Solution

  • It's an integer. Refer to the file like this.

    int song1 = R.raw.testsound;
    MediaPlayer testPlayer = MediaPlayer.create(this, song1);
    

    But using a URI is more the way to go