Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sound file as variable in android MediaPlayer

Tags:

java

android

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");
like image 544
JPJens Avatar asked Jul 31 '15 11:07

JPJens


1 Answers

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.

like image 193
Hiren Patel Avatar answered Oct 31 '22 13:10

Hiren Patel