Reputation: 195
I have may file.wav in my directory. Then in parallel, I have to play is with an mp3 file.
See the code below:
String recordedFile = "/storage/sdcard0/app/file.wav";
MediaPlayer recordedSong = new MediaPlayer();
try {
recordedSong = MediaPlayer.create(ctx,
Uri.fromFile(recordedFile));
recordedSong.prepare();
recordedSong.start();
}
catch (Exception e) {
}
Error: Creation failed and it throws IOException
Upvotes: 11
Views: 29056
Reputation: 5468
This works for me (Kotlin):
val mediaPlayer = MediaPlayer.create(
context,
R.raw.sound)
mediaPlayer.start()
Upvotes: 4
Reputation: 579
I've tried @aangwi answer but got FileNodeFoundException
final AssetFileDescriptor afd = myactivity.getResources().openRawResourceFd(R.raw.your_file);
final FileDescriptor fileDescriptor = afd.getFileDescriptor();
MediaPlayer player = new MediaPlayer();
try {
player.setDataSource(fileDescriptor, afd.getStartOffset(),
afd.getLength());
player.setLooping(false);
player.prepare();
player.start();
} catch (IOException ex) {
LOGGER.error(ex.getLocalizedMessage(), ex);
}
Upvotes: 8
Reputation: 126
Try to create raw folder and put your file there, use this
public void number(int num, Context ctx) {
AssetManager am;
try {
am = ctx.getAssets();
AssetFileDescriptor afd = am.openFd("android.resource://"+getPackageName+"/"+R.raw.your_file_name);
player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),
afd.getLength());
player.prepare();
player.start();
player.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
player.setLooping(false);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Upvotes: 11