6

While in the process of learning android/java i wanted to create a function that could play a specefic sound from the raw folder.

I am attempting to define the sound-file as a string, so that the function can be reused. However i am stuck with "Cannot resolve symbol".

public class MainActivity extends ActionBarActivity {
MediaPlayer player;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    playSound("dogBark");
}

public void playSound(String soundFile) {
    player = MediaPlayer.create(MainActivity.this,R.raw.soundFile); // Cannot resolve symbol 'soundFile'
    player.setLooping(true);
    player.start();

}
...

I am sure this is a basic lack-of-knowledge issue, but any help is greatly appreciated.

Edit:

The above function works well if i add the actual sound file in the function:

player = MediaPLayer.create(MainActivity.this,R.raw.dogBark);

But what i am trying to do is to define the sound file when i call the function instead:

playSound("dogBark");
JPJens
  • 1,185
  • 1
  • 17
  • 39

1 Answers1

10

You can do this way, it works fine for me:

playMp3("titanic");

Add this method:

private void playMp3(String nameOfFile){
   MediaPlayer mPlayer = MediaPlayer.create(this, getResources().getIdentifier(nameOfFile, "raw", getPackageName()));
   mPlayer.start();
}

It would definite work for you.

Hiren Patel
  • 52,124
  • 21
  • 173
  • 151
  • 1
    Perfect. Thank you very much – JPJens Aug 04 '15 at 07:10
  • Please keep in mind to not to try to refer to the file with extension, otherwise the resource ID will not works. Use instead eg. "myString = filename.split("\\.") and then use myString[0] as nameOfFile – RikiRiocma Sep 16 '19 at 09:03