--

Tuesday, 7 February 2017

Audio & Screen recorder utility


 Android OS provides the user recording the Audio and play programmatically from Android App itself. In addition, Android support Screen recording API from API 21. I explain the detail procedure to implement media processing in Android.



Recording & playing Audio

Step 1: Add user permission to manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature    android:name="android.hardware.camera"    android:required="true" />
<uses-feature    android:name="android.hardware.camera.autofocus"    android:required="false" />
<uses-feature    android:name="android.hardware.camera.front"    android:required="false" />

<uses-feature    android:glEsVersion="0x00020000"    android:required="true" />

Step 2:  Check Audio permission
ContextCompat.checkSelfPermission(getApplicationContext(), WRITE_EXTERNAL_STORAGE);
ContextCompat.checkSelfPermission(getApplicationContext(), RECORD_AUDIO);
We have to check write storage & record audio permission. If permission is not enabled,
ActivityCompat.requestPermissions(MainActivity.this, new String[]{
        WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, AUDIO_REQ_PERMISSION_CODE);

Step 3: Initialize media recorder for Audio
mediaRecorder=new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
String strAudiofile=getAudioFileName();
mediaRecorder.setOutputFile(strAudiofile);
 We have to prepare media recorder & start recording audio.
try{
    mediaRecorder.prepare();
    mediaRecorder.start();
}
catch (IllegalStateException e)
{
    Log.e(TAG,"Audio record excep:"+e.getMessage());
} catch (IOException e)
{
    Log.e(TAG,"Audio record excep:"+e.getMessage());
}
Step 5: Posting recording time to progress bar
// Post the record progress : handler.post(UpdateRecordTime);
Runnable UpdateRecordTime=new Runnable(){
    public void run(){
        if(isRecording){
            recordTime+=1;
            mNumberProgress.setProgress(recordTime);
            // Delay 1s before next call            handler.postDelayed(this, 1000);
        }
    }
};

Step 4: Auto - stop recorder using Handler

new Handler().postDelayed(new Runnable() {
    @Override    public void run() {
        imgAudioPlay.setVisibility(View.VISIBLE);
        isRecording=false;
        mediaRecorder.stop();
        Toast.makeText(MainActivity.this, "Recording Completed.", Toast.LENGTH_SHORT).show();
    }
},maxDuration);
 Step 5: Play recorded audio using MediaPlayer
mediaPlayer = new MediaPlayer();

try {
    String strAudiofile=getAudioFileName();
    mediaPlayer.setDataSource(strAudiofile);
    mediaPlayer.prepare();
} catch (IOException e) {
    e.printStackTrace();
}

mediaPlayer.start();
Step 6: Reset Handler & Stop media recorder
Once we re-record audio next time, we have to remove added callbacks from Handler. Mean while we must release mediaRecorder & mediaPlayer as well.
if(handler!=null){
    handler.removeCallbacks(UpdatePlayTime);
    handler.removeCallbacks(UpdateRecordTime);
}
if (null != mediaRecorder) {
    if(isRecording) mediaRecorder.stop();
    mediaRecorder.reset();
    mediaRecorder.release();
    mediaRecorder = null;

    if(mediaPlayer!=null){
        mediaPlayer.reset();
        mediaPlayer.release();
        mediaPlayer=null;
    }
}

Screen Recording & playing video

Step 1:  minSDK must be 21 for recording Screen. in build.gradle

Step 2: Check permission for Audio & write external storage
ActivityCompat.requestPermissions(MainActivity.this,
        new String[]{Manifest.permission
                .WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO},
        VIDEO_REQ_PERMISSION_CODE);
Step 3: Initialize MediaProjectionManager
mProjectionManager = (MediaProjectionManager)mContext.getSystemService
        (Context.MEDIA_PROJECTION_SERVICE);
We have to register the callback for MediaProjectionManager & create a virtual display for video surface.
mMediaProjectionCallback = new MediaProjectionCallback();
mMediaProjection = mProjectionManager.getMediaProjection(resultCode, data);
mMediaProjection.registerCallback(mMediaProjectionCallback, null);
private VirtualDisplay createVirtualDisplay() {
    return mMediaProjection.createVirtualDisplay("Screen recording",
            DISPLAY_WIDTH, DISPLAY_HEIGHT, mScreenDensity,
            DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
            mMediaRecorder.getSurface(), null /*Callbacks*/, null            /*Handler*/);
}
Step 4: Preparing Media Recorder for Video
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
String fileName=getVideoFileName();
mMediaRecorder.setOutputFile(fileName);
mMediaRecorder.setVideoSize(DISPLAY_WIDTH, DISPLAY_HEIGHT);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
//mMediaRecorder.setVideoEncodingBitRate(512 * 1000); // 6000000mMediaRecorder.setVideoEncodingBitRate(6000000);
mMediaRecorder.setVideoFrameRate(30);
int rotation =mActivity.getWindowManager().getDefaultDisplay().getRotation();
int orientation = ORIENTATIONS.get(rotation + 90);
mMediaRecorder.setOrientationHint(orientation);
mMediaRecorder.prepare();
 The Audio source must be CAMCORDER to record audio of the device as well.
 Step 5: Start record video
if (mMediaProjection == null) {
    mActivity.startActivityForResult(mProjectionManager.createScreenCaptureIntent(), REQUEST_CODE);
    return;
}
mVirtualDisplay = createVirtualDisplay();
mMediaRecorder.start();
 Step 6: Play recorded video
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(videoFile));
intent.setDataAndType(Uri.parse(videoFile), "video/mp4");
startActivity(intent);
You find the complete source code from below GitHub path,
https://github.com/JayaprakashR-Zealot/AudVidRecorder

You can raise your queries in the comment section.

Happy coding!!!
Thanks!!!!

No comments:

Post a Comment