10

I already have a .wav file in my directory. at the same time i need to play it together with a mp3 file. I used,

String recordedFile = "/storage/sdcard0/PINOYKARAOKE/1373597371359.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

ceosilvajr
  • 185
  • 1
  • 2
  • 10

3 Answers3

11

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();
        } 
    }
aangwi
  • 126
  • 1
  • 4
  • Why are you using int num as parameter if you never use that parameter? – Windgate Apr 12 '22 at 12:35
  • @Windgate Maybe he removed the unimportant logic for this question but didn't change method signature to be able to test it without breaking the whole project:) – Tamim Attafi Sep 23 '22 at 18:38
7

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);
}
nicolas-f
  • 539
  • 7
  • 17
4

This works for me (Kotlin):

val mediaPlayer = MediaPlayer.create(
                    context,
                    R.raw.sound)
mediaPlayer.start()
Manuel Schmitzberger
  • 5,162
  • 3
  • 36
  • 45
  • I don't have a /raw foldear created in /Resources, but even if I create it and store a file there with the name sound.wav this doesn't create the R.raw.sound ID for me so my app can't play it – Windgate Apr 12 '22 at 12:39