Search code examples
javaandroidaudioandroid-mediarecorder

How to ON or OFF audio recording using MediaRecorder


I'm implement one demo Video and Audio recording using MediaRecorder

Download the demo from hear : Android MediaRecorder Sample

There is one method prepareVideoRecorder() in MainActivity.java. in this method initialization and set Source Audio and video like:

mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

Now i want to audio ON or OFF functionality.

For that i'll tried like this :

 if (!AppSetting.getValue(activity, Config.AUDIO, false)) {
            mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        }else {
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        }

But app is Crash with below error :

java.lang.IllegalStateException
at android.media.MediaRecorder.setAudioEncoder(Native Method)

So how to i solve this error or there is another solution for Audio ON or OFF:


Solution

  • I Got the solution:


    If my switch is ON then if part execute(Sound is record). if my switch is OFF then else part execute(Sound do not record).


    if (AppSetting.getValue(activity, Config.AUDIO, false)) {
                mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
                mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                mMediaRecorder.setMaxDuration(duration);
                mMediaRecorder.setProfile(profile);
            } else {
                mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
                mMediaRecorder.setOutputFormat(profile.fileFormat);
                mMediaRecorder.setVideoEncoder(profile.videoCodec);
                mMediaRecorder.setVideoEncodingBitRate(profile.videoBitRate);
                mMediaRecorder.setVideoFrameRate(profile.videoFrameRate);
                mMediaRecorder.setVideoSize(profile.videoFrameWidth, profile.videoFrameHeight);
                mMediaRecorder.setMaxDuration(duration);
            }