Friday, November 29, 2013

How to Get the Audio File of the Audio Recorder Intent in Android

When you need to record audio on your android application, you have two options: 1.) To implement your own audio recorder and 2.) To use the default default audio recorder of the android device. For some cases, it is more convenient to use the second option because we would no longer need to do additional coding just to accomplish our goal. So to start the audio recorder, we use an intent:
1:          Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);  
2:          startActivityForResult(intent, RECORD_SOUND);  
Please note that the RECORD_SOUND variable is just any integer that serves as the request code for our Audio Record activity so we would know if the result we receive is from that activity.  We use it on this section of our MainActivity's code:
1:       protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
2:            switch(requestCode) {  
3:                 case RECORD_SOUND:  
4:                      /*  
5:                       * get the recorded file's path if resultCode is ok  
6:                       */  
7:                      break;  
8:                 default:  
9:                      super.onActivityResult(requestCode, resultCode, data);  
10:                      break;  
11:            }  
12:       }  

To get the path of the recorded audio most guides use this code:
1:  data.getData().getPath()  
However, when I tried using the value of the path returned by that method, I noticed that the file cannot be accessed. After a bit of digging around, I saw this method to get the actual path:
1:       private String getAudioFileRealPath(Intent data) {  
2:            String realPath = "";  
3:            String[] filePathColumn = { MediaStore.Images.Media.DATA };  
4:            Cursor cursor = getContentResolver().query(data.getData(), filePathColumn, null, null, null);   
5:            if(cursor.moveToFirst()){  
6:              int columnIndex = cursor.getColumnIndex(filePathColumn[0]);  
7:              realPath = cursor.getString(columnIndex);  
8:            }  
9:            cursor.close();  
10:            return realPath;  
11:       }  
Here is a comparison of the paths obtained:

The full source code for this tutorial can be found here

No comments:

Post a Comment