Search code examples
androidcameraandroid-mediarecorderandroid-camera2

How to stop MediaRecorder after certain time in Android?


I want to stop recording a video after a certain time e.g. 5 seconds.
Do you know how to do that with a MediaRecorder?


Solution

  • You can use a handler to step the recording after that time.

    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            recorder.stop();
        }
    }, DELAY);
    

    Regarding the timer:

    int t = 0;
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            textView.setText(getString(R.string.formatted_time, t));
            if(++t<10) {
                handler.postDelayed(this, 1000);
            }
        }
    }, 1000);
    

    Where formatted_time is something like that:

    <string android:name="formatted_time">%d seconds</string>