-1

How can I define file path in MediaPlayer.create() using variable?

I'am developing my first game for Android. My goal is to play different audio files during app execution. I have some files like:

-sound1.mp3 -sound2.mp3 -sound3.mp3

They are in my /res/raw/ project folder.

And I would like my code to be able to choose a file path.

For example (once not working):

for(int i=0; i>3; i++) { 
MediaPlayer mediaPlayer=MediaPlayer.create(getApplicationContext(), R.raw.sound + "" + i;
mediaPlayer.start();
}
Eng Sufyan
  • 19
  • 5

2 Answers2

0

To pass raw resources to MediaPlayer.create() use your application resource variable R.raw.*. For example:

MediaPlayer mediaPlayer = MediaPlayer.create(getContext(), R.raw.sound1);

Please consider reading more about Android Resources because passing file paths of Resources doesn't make sense because Raw Resources are not stored as files.

Dan S
  • 9,139
  • 3
  • 37
  • 48
  • I try to do this but my application stooped : – Eng Sufyan Dec 03 '15 at 18:38
  • I try to do this but my application is stooped : String num="1"; String raw_path="‪raw‬"+"."+"sound"+num; Uri path=Uri.parse(raw_path); mp1 = MediaPlayer.create(getContext(),path); mp1.start(); – Eng Sufyan Dec 03 '15 at 18:42
0

I suffered from the same problem.

But there is a good answer for it:

mediaPlayer.create(contex, variable uri)

You may have a look at this SO answer.

Community
  • 1
  • 1
AhuraMazda
  • 460
  • 4
  • 22