Android, How to play WAV file programmatically

ceosilvajr picture ceosilvajr · Jul 12, 2013 · Viewed 21.2k times · Source

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

Answer

aangwi picture aangwi · Jul 12, 2013

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();
        } 
    }