Skip to content Skip to sidebar Skip to footer

How To Play Recorded Audio File From 'onactivityresult()'?

I'm using this library to record audio in my app. Here's my code: recordDefectAudio.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view)

Solution 1:

Use MediaPlayer to play audio file, write the below code in onActivityResult() , if (resultCode == RESULT_OK) get the path to the audio file from intent data

MediaPlayer mp=new MediaPlayer();  
    try{  
        mp.setDataSource("/sdcard/Music/maine.mp3");//path to your audio file here  
        mp.prepare();  
        mp.start();  

    }catch(Exception e){e.printStackTrace();}  

}  

See this for more info

Solution 2:

protectedvoidonActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == RECORD_PRODUCT_DAMAGE) {
        if (resultCode == RESULT_OK) {
            // Great! User has recorded and saved the audio file
            Toast.makeText(this, "Audio recorded successfully!", Toast.LENGTH_SHORT).show();
            playRecordedAudio.setVisibility(View.VISIBLE);
            recordAgain.setVisibility(View.VISIBLE);
            recordDefectAudio.setVisibility(View.INVISIBLE);

    StringrealPath=null;
    UriuriPath=null;
    realPath = getPathForAudio(YourActivity.this, data.getData());
    uriPath = Uri.fromFile(newFile(realPath)); 
    try{
    MediaPlayermp= MediaPlayer.create(context, uriPath);
    mp.start();
    }catch(NullPointerException e) {
    // handle NullPointerException
    }
        } elseif (resultCode == RESULT_CANCELED) {
            // Oops! User has canceled the recording
            Toast.makeText(this, "Audio was not recorded", Toast.LENGTH_SHORT).show();
        }

    }
}

Then get Audio file path

publicstaticString getPathForAudio(Context context, Uri uri)
 {
  String result = null;
  Cursor cursor = null;

  try {
    String[] proj = { MediaStore.Audio.Media.DATA };
    cursor = context.getContentResolver().query(uri, proj, null, null, null);
    if (cursor == null) {
        result = uri.getPath();
    } else {
        cursor.moveToFirst();
        int column_index = cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);
        result = cursor.getString(column_index);
        cursor.close();
    }
}
catch (Exception e)
{
    e.printStackTrace();
}
finally {
    if (cursor != null) {
        cursor.close();
    }
}
return result;
}

Post a Comment for "How To Play Recorded Audio File From 'onactivityresult()'?"