0

I am trying to load/play a sound (I have file /res/raw/fx2.wav) with the code:

MediaPlayer mp = MediaPlayer.create(this, R.raw.fx2);

or

MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.fx2);

And i get this error:

java.io.IOException: Prepare failed.: status=0x1

I searched this error but none of the answers had working code. Such examples also had:

MediaPlayer mediaPlayer = new MediaPlayer();

and then something with: FileInputStream or mp.setDataSrouce

I am experimenting with these but I have nothing working so far and I don't know what method is best for me or in what situations they should be used? I simply want to load and play a sound.

It might be I am just not getting the context properly. Or there is something wrong with my sound file(but it is a normal small way so I think it is not this).

Any ideas?

kritikaTalwar
  • 1,730
  • 1
  • 17
  • 25
Coder J
  • 1
  • 1

2 Answers2

0

You should have a permission for reading files from external memory in your AndroidManifest.xml file.

<manifest ...>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
...
</manifest>

You should also try to change the path to your file using following code (change com.example.myapp to your package name):

MediaPlayer mp = new MediaPlayer();
Uri uri = Uri.parse("android.resource://com.example.myapp/" + R.raw.fx2);
mp.setDataSourceUri(this, uri);

See this answer for details.

Community
  • 1
  • 1
snitsaruk
  • 422
  • 6
  • 13
0

This worked for me:

MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.beep);
mediaPlayer.start();

Make sure you are importing:

import android.media.MediaPlayer;
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Mahesh Shahane
  • 489
  • 5
  • 16