MediaRecorder

public class MediaRecorder
extends Object implements AudioRouting, AudioRecordingMonitor, MicrophoneDirection

java.lang.Object
   ↳ android.media.MediaRecorder


Used to record audio and video. The recording control is based on a simple state machine (see below).

A common case of using MediaRecorder to record audio works as follows:

MediaRecorder recorder = new MediaRecorder();
 recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
 recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
 recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
 recorder.setOutputFile(PATH_NAME);
 recorder.prepare();
 recorder.start();   // Recording is now started
 ...
 recorder.stop();
 recorder.reset();   // You can reuse the object by going back to setAudioSource() step
 recorder.release(); // Now the object cannot be reused
 

Applications may want to register for informational and error events in order to be informed of some internal update and possible runtime errors during recording. Registration for such events is done by setting the appropriate listeners (via calls (to setOnInfoListener(android.media.MediaRecorder.OnInfoListener)setOnInfoListener and/or setOnErrorListener(android.media.MediaRecorder.OnErrorListener)setOnErrorListener). In order to receive the respective callback associated with these listeners, applications are required to create MediaRecorder objects on threads with a Looper running (the main UI thread by default already has a Looper running).

Note: Currently, MediaRecorder does not work on the emulator.

Developer Guides

For more information about how to use MediaRecorder for recording video, read the Camera developer guide. For more information about how to use MediaRecorder for recording sound, read the Audio Capture developer guide.

Summary

Nested classes

class MediaRecorder.AudioEncoder

Defines the audio encoding. 

class MediaRecorder.AudioSource

Defines the audio source. 

class MediaRecorder.MetricsConstants

 

interface MediaRecorder.OnErrorListener

Interface definition for a callback to be invoked when an error occurs while recording. 

interface MediaRecorder.OnInfoListener

Interface definition of a callback to be invoked to communicate some info and/or warning about the recording. 

class MediaRecorder.OutputFormat

Defines the output format. 

class MediaRecorder.VideoEncoder

Defines the video encoding. 

class MediaRecorder.VideoSource

Defines the video source. 

Constants

int MEDIA_ERROR_SERVER_DIED

Media server died.

int MEDIA_RECORDER_ERROR_UNKNOWN

Unspecified media recorder error.

int MEDIA_RECORDER_INFO_MAX_DURATION_REACHED

A maximum duration had been setup and has now been reached.

int MEDIA_RECORDER_INFO_MAX_FILESIZE_APPROACHING

A maximum filesize had been setup and current recorded file size has reached 90% of the limit.

int MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED

A maximum filesize had been setup and has now been reached.

int MEDIA_RECORDER_INFO_NEXT_OUTPUT_FILE_STARTED

A maximum filesize had been reached and MediaRecorder has switched output to a new file set by application setNextOutputFile(File).

int MEDIA_RECORDER_INFO_UNKNOWN

Unspecified media recorder info.

Inherited constants

Public constructors

MediaRecorder()

This constructor is deprecated. Use MediaRecorder(android.content.Context) instead

MediaRecorder(Context context)

Default constructor.

Public methods

void addOnRoutingChangedListener(AudioRouting.OnRoutingChangedListener listener, Handler handler)

Adds an AudioRouting.OnRoutingChangedListener to receive notifications of routing changes on this MediaRecorder.

List<MicrophoneInfo> getActiveMicrophones()

Return A lists of MicrophoneInfo representing the active microphones.

AudioRecordingConfiguration getActiveRecordingConfiguration()

Returns the current active audio recording for this audio recorder.

static final int getAudioSourceMax()

Gets the maximum value for audio sources.

LogSessionId getLogSessionId()

Returns the LogSessionId for MediaRecorder.

int getMaxAmplitude()

Returns the maximum absolute amplitude that was sampled since the last call to this method.

PersistableBundle getMetrics()

Return Metrics data about the current Mediarecorder instance.

AudioDeviceInfo getPreferredDevice()

Returns the selected input device specified by setPreferredDevice(AudioDeviceInfo).

AudioDeviceInfo getRoutedDevice()

Returns an AudioDeviceInfo identifying the current routing of this MediaRecorder Note: The query is only valid if the MediaRecorder is currently recording.

Surface getSurface()

Gets the surface to record from when using SURFACE video source.

boolean isPrivacySensitive()

Returns whether this MediaRecorder is marked as privacy sensitive or not with regard to audio capture.

void pause()

Pauses recording.

void prepare()

Prepares the recorder to begin capturing and encoding data.

void registerAudioRecordingCallback(Executor executor, AudioManager.AudioRecordingCallback cb)

Register a callback to be notified of audio capture changes via a AudioManager.AudioRecordingCallback.

void release()

Releases resources associated with this MediaRecorder object.

void removeOnRoutingChangedListener(AudioRouting.OnRoutingChangedListener listener)

Removes an AudioRouting.OnRoutingChangedListener which has been previously added to receive rerouting notifications.

void reset()

Restarts the MediaRecorder to its idle state.

void resume()

Resumes recording.

void setAudioChannels(int numChannels)

Sets the number of audio channels for recording.

void setAudioEncoder(int audio_encoder)

Sets the audio encoder to be used for recording.

void setAudioEncodingBitRate(int bitRate)

Sets the audio encoding bit rate for recording.

void setAudioProfile(EncoderProfiles.AudioProfile profile)

Uses the settings from an AudioProfile for recording.

void setAudioSamplingRate(int samplingRate)

Sets the audio sampling rate for recording.

void setAudioSource(int audioSource)

Sets the audio source to be used for recording.

void setCamera(Camera c)

This method was deprecated in API level 21. Use getSurface() and the android.hardware.camera2 API instead.

void setCaptureRate(double fps)

Set video frame capture rate.

void setInputSurface(Surface surface)

Configures the recorder to use a persistent surface when using SURFACE video source.

void setLocation(float latitude, float longitude)

Set and store the geodata (latitude and longitude) in the output file.

void setLogSessionId(LogSessionId id)

Sets the LogSessionId for MediaRecorder.

void setMaxDuration(int max_duration_ms)

Sets the maximum duration (in ms) of the recording session.

void setMaxFileSize(long max_filesize_bytes)

Sets the maximum filesize (in bytes) of the recording session.

void setNextOutputFile(File file)

Sets the next output file to be used when the maximum filesize is reached on the prior output setOutputFile(File) or setNextOutputFile(File)).

void setNextOutputFile(FileDescriptor fd)

Sets the next output file descriptor to be used when the maximum filesize is reached on the prior output setOutputFile(File) or setNextOutputFile(File)).

void setOnErrorListener(MediaRecorder.OnErrorListener l)

Register a callback to be invoked when an error occurs while recording.

void setOnInfoListener(MediaRecorder.OnInfoListener listener)

Register a callback to be invoked when an informational event occurs while recording.

void setOrientationHint(int degrees)

Sets the orientation hint for output video playback.

void setOutputFile(FileDescriptor fd)

Pass in the file descriptor of the file to be written.

void setOutputFile(String path)

Sets the path of the output file to be produced.

void setOutputFile(File file)

Pass in the file object to be written.

void setOutputFormat(int output_format)

Sets the format of the output file produced during recording.

boolean setPreferredDevice(AudioDeviceInfo deviceInfo)

Specifies an audio device (via an AudioDeviceInfo object) to route the input from this MediaRecorder.

boolean setPreferredMicrophoneDirection(int direction)

Specifies the logical microphone (for processing).

boolean setPreferredMicrophoneFieldDimension(float zoom)

Specifies the zoom factor (i.e.

void setPreviewDisplay(Surface sv)

Sets a Surface to show a preview of recorded media (video).

void setPrivacySensitive(boolean privacySensitive)

Indicates that this capture request is privacy sensitive and that any concurrent capture is not permitted.

void setProfile(CamcorderProfile profile)

Uses the settings from a CamcorderProfile object for recording.

void setVideoEncoder(int video_encoder)

Sets the video encoder to be used for recording.

void setVideoEncodingBitRate(int bitRate)

Sets the video encoding bit rate for recording.

void setVideoEncodingProfileLevel(int profile, int level)

Sets the desired video encoding profile and level for recording.

void setVideoFrameRate(int rate)

Sets the frame rate of the video to be captured.

void setVideoProfile(EncoderProfiles.VideoProfile profile)

Uses the settings from a VideoProfile object for recording.

void setVideoSize(int width, int height)

Sets the width and height of the video to be captured.

void setVideoSource(int video_source)

Sets the video source to be used for recording.

void start()

Begins capturing and encoding data to the file specified with setOutputFile().

void stop()

Stops recording.

void unregisterAudioRecordingCallback(AudioManager.AudioRecordingCallback cb)

Unregister an audio recording callback previously registered with registerAudioRecordingCallback(java.util.concurrent.Executor, android.media.AudioManager.AudioRecordingCallback).

Protected methods

void finalize()

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

Inherited methods

Constants

MEDIA_ERROR_SERVER_DIED

Added in API level 17
public static final int MEDIA_ERROR_SERVER_DIED

Media server died. In this case, the application must release the MediaRecorder object and instantiate a new one.

Constant Value: 100 (0x00000064)

MEDIA_RECORDER_ERROR_UNKNOWN

Added in API level 3
public static final int MEDIA_RECORDER_ERROR_UNKNOWN

Unspecified media recorder error.

Constant Value: 1 (0x00000001)

MEDIA_RECORDER_INFO_MAX_DURATION_REACHED

Added in API level 3
public static final int MEDIA_RECORDER_INFO_MAX_DURATION_REACHED

A maximum duration had been setup and has now been reached.

Constant Value: 800 (0x00000320)

MEDIA_RECORDER_INFO_MAX_FILESIZE_APPROACHING

Added in API level 26
public static final int MEDIA_RECORDER_INFO_MAX_FILESIZE_APPROACHING

A maximum filesize had been setup and current recorded file size has reached 90% of the limit. This is sent once per file upon reaching/passing the 90% limit. To continue the recording, applicaiton should use setNextOutputFile(File) to set the next output file. Otherwise, recording will stop when reaching maximum file size.

Constant Value: 802 (0x00000322)

MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED

Added in API level 3
public static final int MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED

A maximum filesize had been setup and has now been reached. Note: This event will not be sent if application already set next output file through setNextOutputFile(File).

Constant Value: 801 (0x00000321)

MEDIA_RECORDER_INFO_NEXT_OUTPUT_FILE_STARTED

Added in API level 26
public static final int MEDIA_RECORDER_INFO_NEXT_OUTPUT_FILE_STARTED

A maximum filesize had been reached and MediaRecorder has switched output to a new file set by application setNextOutputFile(File). For best practice, application should use this event to keep track of whether the file previously set has been used or not.

Constant Value: 803 (0x00000323)

MEDIA_RECORDER_INFO_UNKNOWN

Added in API level 3
public static final int MEDIA_RECORDER_INFO_UNKNOWN

Unspecified media recorder info.

Constant Value: 1 (0x00000001)

Public constructors

MediaRecorder

Added in API level 1
public MediaRecorder ()

This constructor is deprecated.
Use MediaRecorder(android.content.Context) instead

Default constructor.

MediaRecorder

Added in API level 1
public MediaRecorder (Context context)

Default constructor.

Parameters
context Context: Context the recorder belongs to This value cannot be null.

Public methods

addOnRoutingChangedListener

Added in API level 28
public void addOnRoutingChangedListener (AudioRouting.OnRoutingChangedListener listener, 
                Handler handler)

Adds an AudioRouting.OnRoutingChangedListener to receive notifications of routing changes on this MediaRecorder.

Parameters
listener AudioRouting.OnRoutingChangedListener: The AudioRouting.OnRoutingChangedListener interface to receive notifications of rerouting events.

handler Handler: Specifies the Handler object for the thread on which to execute the callback. If null, the handler on the main looper will be used.

getActiveMicrophones

Added in API level 28
public List<MicrophoneInfo> getActiveMicrophones ()

Return A lists of MicrophoneInfo representing the active microphones. By querying channel mapping for each active microphone, developer can know how the microphone is used by each channels or a capture stream.

Returns
List<MicrophoneInfo> a lists of MicrophoneInfo representing the active microphones

Throws
IOException if an error occurs

getActiveRecordingConfiguration

Added in API level 29
public AudioRecordingConfiguration getActiveRecordingConfiguration ()

Returns the current active audio recording for this audio recorder.

Returns
AudioRecordingConfiguration a valid AudioRecordingConfiguration if this recorder is active or null otherwise.

getAudioSourceMax

Added in API level 4
public static final int getAudioSourceMax ()

Gets the maximum value for audio sources.

Returns
int

getLogSessionId

Added in API level 31
public LogSessionId getLogSessionId ()

Returns the LogSessionId for MediaRecorder.

Returns
LogSessionId the global ID for monitoring the MediaRecorder performance This value cannot be null.

getMaxAmplitude

Added in API level 1
public int getMaxAmplitude ()

Returns the maximum absolute amplitude that was sampled since the last call to this method. Call this only after the setAudioSource().

Returns
int the maximum absolute amplitude measured since the last call, or 0 when called for the first time

Throws
IllegalStateException if it is called before the audio source has been set.

getMetrics

Added in API level 26
public PersistableBundle getMetrics ()

Return Metrics data about the current Mediarecorder instance.

Returns
PersistableBundle a PersistableBundle containing the set of attributes and values available for the media being generated by this instance of MediaRecorder. The attributes are descibed in MetricsConstants. Additional vendor-specific fields may also be present in the return value.

getPreferredDevice

Added in API level 28
public AudioDeviceInfo getPreferredDevice ()

Returns the selected input device specified by setPreferredDevice(AudioDeviceInfo). Note that this is not guaranteed to correspond to the actual device being used for recording.

Returns
AudioDeviceInfo

getRoutedDevice

Added in API level 28
public AudioDeviceInfo getRoutedDevice ()

Returns an AudioDeviceInfo identifying the current routing of this MediaRecorder Note: The query is only valid if the MediaRecorder is currently recording. If the recorder is not recording, the returned device can be null or correspond to previously selected device when the recorder was last active.

Returns
AudioDeviceInfo

getSurface

Added in API level 21
public Surface getSurface ()

Gets the surface to record from when using SURFACE video source.

May only be called after prepare(). Frames rendered to the Surface before start() will be discarded.

Returns
Surface

Throws
IllegalStateException if it is called before prepare(), after stop(), or is called when VideoSource is not set to SURFACE.

isPrivacySensitive

Added in API level 30
public boolean isPrivacySensitive ()

Returns whether this MediaRecorder is marked as privacy sensitive or not with regard to audio capture.

See setPrivacySensitive(boolean)

Returns
boolean true if privacy sensitive, false otherwise

pause

Added in API level 24
public void pause ()

Pauses recording. Call this after start(). You may resume recording with resume() without reconfiguration, as opposed to stop(). It does nothing if the recording is already paused. When the recording is paused and resumed, the resulting output would be as if nothing happend during paused period, immediately switching to the resumed scene.

Throws
IllegalStateException if it is called before start() or after stop()

prepare

Added in API level 1
public void prepare ()

Prepares the recorder to begin capturing and encoding data. This method must be called after setting up the desired audio and video sources, encoders, file format, etc., but before start().

Throws
IllegalStateException if it is called after start() or before setOutputFormat().
IOException if prepare fails otherwise.

registerAudioRecordingCallback

Added in API level 29
public void registerAudioRecordingCallback (Executor executor, 
                AudioManager.AudioRecordingCallback cb)

Register a callback to be notified of audio capture changes via a AudioManager.AudioRecordingCallback. A callback is received when the capture path configuration changes (pre-processing, format, sampling rate...) or capture is silenced/unsilenced by the system.

Parameters
executor Executor: Executor to handle the callbacks. This value cannot be null. Callback and listener events are dispatched through this Executor, providing an easy way to control which thread is used. To dispatch events through the main thread of your application, you can use Context.getMainExecutor(). Otherwise, provide an Executor that dispatches to an appropriate thread.

cb AudioManager.AudioRecordingCallback: non-null callback to register

release

Added in API level 1
public void release ()

Releases resources associated with this MediaRecorder object. It is good practice to call this method when you're done using the MediaRecorder. In particular, whenever an Activity of an application is paused (its onPause() method is called), or stopped (its onStop() method is called), this method should be invoked to release the MediaRecorder object, unless the application has a special need to keep the object around. In addition to unnecessary resources (such as memory and instances of codecs) being held, failure to call this method immediately if a MediaRecorder object is no longer needed may also lead to continuous battery consumption for mobile devices, and recording failure for other applications if no multiple instances of the same codec are supported on a device. Even if multiple instances of the same codec are supported, some performance degradation may be expected when unnecessary multiple instances are used at the same time.

removeOnRoutingChangedListener

Added in API level 28
public void removeOnRoutingChangedListener (AudioRouting.OnRoutingChangedListener listener)

Removes an AudioRouting.OnRoutingChangedListener which has been previously added to receive rerouting notifications.

Parameters
listener AudioRouting.OnRoutingChangedListener: The previously added AudioRouting.OnRoutingChangedListener interface to remove.

reset

Added in API level 1
public void reset ()

Restarts the MediaRecorder to its idle state. After calling this method, you will have to configure it again as if it had just been constructed.

resume

Added in API level 24
public void resume ()

Resumes recording. Call this after start(). It does nothing if the recording is not paused.

Throws
IllegalStateException if it is called before start() or after stop()

See also:

setAudioChannels

Added in API level 8
public void setAudioChannels (int numChannels)

Sets the number of audio channels for recording. Call this method before prepare(). Prepare() may perform additional checks on the parameter to make sure whether the specified number of audio channels are applicable.

Parameters
numChannels int: the number of audio channels. Usually it is either 1 (mono) or 2 (stereo).

setAudioEncoder

Added in API level 1
public void setAudioEncoder (int audio_encoder)

Sets the audio encoder to be used for recording. If this method is not called, the output file will not contain an audio track. Call this after setOutputFormat() but before prepare().

Parameters
audio_encoder int: the audio encoder to use. Value is MediaRecorder.AudioEncoder.DEFAULT, MediaRecorder.AudioEncoder.AMR_NB, MediaRecorder.AudioEncoder.AMR_WB, MediaRecorder.AudioEncoder.AAC, MediaRecorder.AudioEncoder.HE_AAC, MediaRecorder.AudioEncoder.AAC_ELD, MediaRecorder.AudioEncoder.VORBIS, or MediaRecorder.AudioEncoder.OPUS

Throws
IllegalStateException if it is called before setOutputFormat() or after prepare().

setAudioEncodingBitRate

Added in API level 8
public void setAudioEncodingBitRate (int bitRate)

Sets the audio encoding bit rate for recording. Call this method before prepare(). Prepare() may perform additional checks on the parameter to make sure whether the specified bit rate is applicable, and sometimes the passed bitRate will be clipped internally to ensure the audio recording can proceed smoothly based on the capabilities of the platform.

Parameters
bitRate int: the audio encoding bit rate in bits per second.

setAudioProfile

Added in API level 31
public void setAudioProfile (EncoderProfiles.AudioProfile profile)

Uses the settings from an AudioProfile for recording.

This method should be called after the video AND audio sources are set, and before setOutputFile().

This method can be used instead of setProfile(CamcorderProfile) when using EncoderProfiles.

Parameters
profile EncoderProfiles.AudioProfile: the AudioProfile to use This value cannot be null.

setAudioSamplingRate

Added in API level 8
public void setAudioSamplingRate (int samplingRate)

Sets the audio sampling rate for recording. Call this method before prepare(). Prepare() may perform additional checks on the parameter to make sure whether the specified audio sampling rate is applicable. The sampling rate really depends on the format for the audio recording, as well as the capabilities of the platform. For instance, the sampling rate supported by AAC audio coding standard ranges from 8 to 96 kHz, the sampling rate supported by AMRNB is 8kHz, and the sampling rate supported by AMRWB is 16kHz. Please consult with the related audio coding standard for the supported audio sampling rate.

Parameters
samplingRate int: the sampling rate for audio in samples per second.

setAudioSource

Added in API level 1
public void setAudioSource (int audioSource)

Sets the audio source to be used for recording. If this method is not called, the output file will not contain an audio track. The source needs to be specified before setting recording-parameters or encoders. Call this only before setOutputFormat().

Parameters
audioSource int: the audio source to use Value is MediaRecorder.AudioSource.DEFAULT, MediaRecorder.AudioSource.MIC, MediaRecorder.AudioSource.VOICE_UPLINK, MediaRecorder.AudioSource.VOICE_DOWNLINK, MediaRecorder.AudioSource.VOICE_CALL, MediaRecorder.AudioSource.CAMCORDER, MediaRecorder.AudioSource.VOICE_RECOGNITION, MediaRecorder.AudioSource.VOICE_COMMUNICATION, MediaRecorder.AudioSource.UNPROCESSED, or MediaRecorder.AudioSource.VOICE_PERFORMANCE

Throws
IllegalStateException if it is called after setOutputFormat()

setCamera

Added in API level 3
Deprecated in API level 21
public void setCamera (Camera c)

This method was deprecated in API level 21.
Use getSurface() and the android.hardware.camera2 API instead.

Sets a Camera to use for recording.

Use this function to switch quickly between preview and capture mode without a teardown of the camera object. Camera.unlock() should be called before this. Must call before prepare().

Parameters
c Camera: the Camera to use for recording

setCaptureRate

Added in API level 11
public void setCaptureRate (double fps)

Set video frame capture rate. This can be used to set a different video frame capture rate than the recorded video's playback rate. This method also sets the recording mode to time lapse. In time lapse video recording, only video is recorded. Audio related parameters are ignored when a time lapse recording session starts, if an application sets them.

Parameters
fps double: Rate at which frames should be captured in frames per second. The fps can go as low as desired. However the fastest fps will be limited by the hardware. For resolutions that can be captured by the video camera, the fastest fps can be computed using Camera.Parameters.getPreviewFpsRange(int[]). For higher resolutions the fastest fps may be more restrictive. Note that the recorder cannot guarantee that frames will be captured at the given rate due to camera/encoder limitations. However it tries to be as close as possible.

setInputSurface

Added in API level 23
public void setInputSurface (Surface surface)

Configures the recorder to use a persistent surface when using SURFACE video source.

May only be called before prepare(). If called, getSurface() should not be used and will throw IllegalStateException. Frames rendered to the Surface before start() will be discarded.

Parameters
surface Surface: a persistent input surface created by MediaCodec#createPersistentInputSurface This value cannot be null.

Throws
IllegalStateException if it is called after prepare() and before stop().
IllegalArgumentException if the surface was not created by MediaCodec#createPersistentInputSurface.

setLocation

Added in API level 14
public void setLocation (float latitude, 
                float longitude)

Set and store the geodata (latitude and longitude) in the output file. This method should be called before prepare(). The geodata is stored in udta box if the output format is OutputFormat.THREE_GPP or OutputFormat.MPEG_4, and is ignored for other output formats. The geodata is stored according to ISO-6709 standard.

Parameters
latitude float: latitude in degrees. Its value must be in the range [-90, 90].

longitude float: longitude in degrees. Its value must be in the range [-180, 180].

Throws
IllegalArgumentException if the given latitude or longitude is out of range.

setLogSessionId

Added in API level 31
public void setLogSessionId (LogSessionId id)

Sets the LogSessionId for MediaRecorder.

The log session ID is a random 32-byte hexadecimal string that is used for monitoring the MediaRecorder performance.

Parameters
id LogSessionId: the global ID for monitoring the MediaRecorder performance This value cannot be null.

setMaxDuration

Added in API level 3
public void setMaxDuration (int max_duration_ms)

Sets the maximum duration (in ms) of the recording session. Call this after setOutputFormat() but before prepare(). After recording reaches the specified duration, a notification will be sent to the MediaRecorder.OnInfoListener with a "what" code of MEDIA_RECORDER_INFO_MAX_DURATION_REACHED and recording will be stopped. Stopping happens asynchronously, there is no guarantee that the recorder will have stopped by the time the listener is notified.

When using MPEG-4 container (setOutputFormat(int) with OutputFormat#MPEG_4), it is recommended to set maximum duration that fits the use case. Setting a larger than required duration may result in a larger than needed output file because of space reserved for MOOV box expecting large movie data in this recording session. Unused space of MOOV box is turned into FREE box in the output file.

Parameters
max_duration_ms int: the maximum duration in ms (if zero or negative, disables the duration limit)

Throws
IllegalArgumentException

setMaxFileSize

Added in API level 3
public void setMaxFileSize (long max_filesize_bytes)

Sets the maximum filesize (in bytes) of the recording session. Call this after setOutputFormat() but before prepare(). After recording reaches the specified filesize, a notification will be sent to the MediaRecorder.OnInfoListener with a "what" code of MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED and recording will be stopped. Stopping happens asynchronously, there is no guarantee that the recorder will have stopped by the time the listener is notified.

When using MPEG-4 container (setOutputFormat(int) with OutputFormat#MPEG_4), it is recommended to set maximum filesize that fits the use case. Setting a larger than required filesize may result in a larger than needed output file because of space reserved for MOOV box expecting large movie data in this recording session. Unused space of MOOV box is turned into FREE box in the output file.

Parameters
max_filesize_bytes long: the maximum filesize in bytes (if zero or negative, disables the limit)

Throws
IllegalArgumentException

setNextOutputFile

Added in API level 26
public void setNextOutputFile (File file)

Sets the next output file to be used when the maximum filesize is reached on the prior output setOutputFile(File) or setNextOutputFile(File)). File should be seekable. After setting the next output file, application should not use the file until stop(). Application must call this after receiving on the MediaRecorder.OnInfoListener a "what" code of MEDIA_RECORDER_INFO_MAX_FILESIZE_APPROACHING and before receiving a "what" code of MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED. The file is not used until switching to that output. Application will receive MEDIA_RECORDER_INFO_NEXT_OUTPUT_FILE_STARTED when the next output file is used. Application will not be able to set a new output file if the previous one has not been used. Application is responsible for cleaning up unused files after stop() is called.

Parameters
file File: The file to use.

Throws
IllegalStateException if it is called before prepare().
IOException if setNextOutputFile fails otherwise.

setNextOutputFile

Added in API level 26
public void setNextOutputFile (FileDescriptor fd)

Sets the next output file descriptor to be used when the maximum filesize is reached on the prior output setOutputFile(File) or setNextOutputFile(File)). File descriptor must be seekable and writable. After setting the next output file, application should not use the file referenced by this file descriptor until stop(). It is the application's responsibility to close the file descriptor. It is safe to do so as soon as this call returns. Application must call this after receiving on the MediaRecorder.OnInfoListener a "what" code of MEDIA_RECORDER_INFO_MAX_FILESIZE_APPROACHING and before receiving a "what" code of MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED. The file is not used until switching to that output. Application will receiveMEDIA_RECORDER_INFO_NEXT_OUTPUT_FILE_STARTED when the next output file is used. Application will not be able to set a new output file if the previous one has not been used. Application is responsible for cleaning up unused files after stop() is called.

Parameters
fd FileDescriptor: an open file descriptor to be written into.

Throws
IllegalStateException if it is called before prepare().
IOException if setNextOutputFile fails otherwise.

setOnErrorListener

Added in API level 3
public void setOnErrorListener (MediaRecorder.OnErrorListener l)

Register a callback to be invoked when an error occurs while recording.

Parameters
l MediaRecorder.OnErrorListener: the callback that will be run

setOnInfoListener

Added in API level 3
public void setOnInfoListener (MediaRecorder.OnInfoListener listener)

Register a callback to be invoked when an informational event occurs while recording.

Parameters
listener MediaRecorder.OnInfoListener: the callback that will be run

setOrientationHint

Added in API level 9
public void setOrientationHint (int degrees)

Sets the orientation hint for output video playback. This method should be called before prepare(). This method will not trigger the source video frame to rotate during video recording, but to add a composition matrix containing the rotation angle in the output video if the output format is OutputFormat.THREE_GPP or OutputFormat.MPEG_4 so that a video player can choose the proper orientation for playback. Note that some video players may choose to ignore the compostion matrix in a video during playback.

Parameters
degrees int: the angle to be rotated clockwise in degrees. The supported angles are 0, 90, 180, and 270 degrees.

Throws
IllegalArgumentException if the angle is not supported.

setOutputFile

Added in API level 3
public void setOutputFile (FileDescriptor fd)

Pass in the file descriptor of the file to be written. Call this after setOutputFormat() but before prepare().

Parameters
fd FileDescriptor: an open file descriptor to be written into.

Throws
IllegalStateException if it is called before setOutputFormat() or after prepare()

setOutputFile

Added in API level 1
public void setOutputFile (String path)

Sets the path of the output file to be produced. Call this after setOutputFormat() but before prepare().

Parameters
path String: The pathname to use.

Throws
IllegalStateException if it is called before setOutputFormat() or after prepare()

setOutputFile

Added in API level 26
public void setOutputFile (File file)

Pass in the file object to be written. Call this after setOutputFormat() but before prepare(). File should be seekable. After setting the next output file, application should not use the file until stop(). Application is responsible for cleaning up unused files after stop() is called.

Parameters
file File: the file object to be written into.

setOutputFormat

Added in API level 1
public void setOutputFormat (int output_format)

Sets the format of the output file produced during recording. Call this after setAudioSource()/setVideoSource() but before prepare().

It is recommended to always use 3GP format when using the H.263 video encoder and AMR audio encoder. Using an MPEG-4 container format may confuse some desktop players.

Parameters
output_format int: the output format to use. The output format needs to be specified before setting recording-parameters or encoders. Value is MediaRecorder.OutputFormat.DEFAULT, MediaRecorder.OutputFormat.THREE_GPP, MediaRecorder.OutputFormat.MPEG_4, MediaRecorder.OutputFormat.AMR_NB, MediaRecorder.OutputFormat.AMR_WB, android.media.MediaRecorder.OutputFormat.AAC_ADIF, MediaRecorder.OutputFormat.AAC_ADTS, MediaRecorder.OutputFormat.MPEG_2_TS, MediaRecorder.OutputFormat.WEBM, android.media.MediaRecorder.OutputFormat.HEIF, or MediaRecorder.OutputFormat.OGG

Throws
IllegalStateException if it is called after prepare() or before setAudioSource()/setVideoSource().

setPreferredDevice

Added in API level 28
public boolean setPreferredDevice (AudioDeviceInfo deviceInfo)

Specifies an audio device (via an AudioDeviceInfo object) to route the input from this MediaRecorder.

Parameters
deviceInfo AudioDeviceInfo: The AudioDeviceInfo specifying the audio source. If deviceInfo is null, default routing is restored.

Returns
boolean true if succesful, false if the specified AudioDeviceInfo is non-null and does not correspond to a valid audio input device.

setPreferredMicrophoneDirection

Added in API level 29
public boolean setPreferredMicrophoneDirection (int direction)

Specifies the logical microphone (for processing).

Parameters
direction int: Direction constant. Value is MicrophoneDirection.MIC_DIRECTION_UNSPECIFIED, MicrophoneDirection.MIC_DIRECTION_TOWARDS_USER, MicrophoneDirection.MIC_DIRECTION_AWAY_FROM_USER, or MicrophoneDirection.MIC_DIRECTION_EXTERNAL

Returns
boolean true if sucessful.

setPreferredMicrophoneFieldDimension

Added in API level 29
public boolean setPreferredMicrophoneFieldDimension (float zoom)

Specifies the zoom factor (i.e. the field dimension) for the selected microphone (for processing). The selected microphone is determined by the use-case for the stream.

Parameters
zoom float: the desired field dimension of microphone capture. Range is from -1 (wide angle), though 0 (no zoom) to 1 (maximum zoom). Value is between -1.0 and 1.0 inclusive

Returns
boolean true if sucessful.

setPreviewDisplay

Added in API level 1
public void setPreviewDisplay (Surface sv)

Sets a Surface to show a preview of recorded media (video). Calls this before prepare() to make sure that the desirable preview display is set. If setCamera(android.hardware.Camera) is used and the surface has been already set to the camera, application do not need to call this. If this is called with non-null surface, the preview surface of the camera will be replaced by the new surface. If this method is called with null surface or not called at all, media recorder will not change the preview surface of the camera.

Parameters
sv Surface: the Surface to use for the preview

setPrivacySensitive

Added in API level 30
public void setPrivacySensitive (boolean privacySensitive)

Indicates that this capture request is privacy sensitive and that any concurrent capture is not permitted.

The default is not privacy sensitive except when the audio source set with setAudioSource(int) is AudioSource#VOICE_COMMUNICATION or AudioSource#CAMCORDER.

Always takes precedence over default from audio source when set explicitly.

Using this API is only permitted when the audio source is one of:

Invoking prepare() will throw an IOException if this condition is not met.

Must be called after setAudioSource(int) and before setOutputFormat(int).

Parameters
privacySensitive boolean: True if capture from this MediaRecorder must be marked as privacy sensitive, false otherwise.

Throws
IllegalStateException if called before setAudioSource(int) or after setOutputFormat(int)

setProfile

Added in API level 8
public void setProfile (CamcorderProfile profile)

Uses the settings from a CamcorderProfile object for recording. This method should be called after the video AND audio sources are set, and before setOutputFile(). If a time lapse CamcorderProfile is used, audio related source or recording parameters are ignored.

Parameters
profile CamcorderProfile: the CamcorderProfile to use

See also:

setVideoEncoder

Added in API level 3
public void setVideoEncoder (int video_encoder)

Sets the video encoder to be used for recording. If this method is not called, the output file will not contain an video track. Call this after setOutputFormat() and before prepare().

Parameters
video_encoder int: the video encoder to use. Value is MediaRecorder.VideoEncoder.DEFAULT, MediaRecorder.VideoEncoder.H263, MediaRecorder.VideoEncoder.H264, MediaRecorder.VideoEncoder.MPEG_4_SP, MediaRecorder.VideoEncoder.VP8, MediaRecorder.VideoEncoder.HEVC, MediaRecorder.VideoEncoder.VP9, MediaRecorder.VideoEncoder.DOLBY_VISION, or MediaRecorder.VideoEncoder.AV1

Throws
IllegalStateException if it is called before setOutputFormat() or after prepare()

setVideoEncodingBitRate

Added in API level 8
public void setVideoEncodingBitRate (int bitRate)

Sets the video encoding bit rate for recording. Call this method before prepare(). Prepare() may perform additional checks on the parameter to make sure whether the specified bit rate is applicable, and sometimes the passed bitRate will be clipped internally to ensure the video recording can proceed smoothly based on the capabilities of the platform.

NB: the actual bitrate and other encoding characteristics may be affected by the minimum quality floor behavior introduced in Build.VERSION_CODES.S. More detail on how and where this impacts video encoding can be found in the MediaCodec page and looking for "quality floor" (near the top of the page).

Parameters
bitRate int: the video encoding bit rate in bits per second.

setVideoEncodingProfileLevel

Added in API level 26
public void setVideoEncodingProfileLevel (int profile, 
                int level)

Sets the desired video encoding profile and level for recording. The profile and level must be valid for the video encoder set by setVideoEncoder(int). This method can called before or after setVideoEncoder(int) but it must be called before prepare(). prepare() may perform additional checks on the parameter to make sure that the specified profile and level are applicable, and sometimes the passed profile or level will be discarded due to codec capablity or to ensure the video recording can proceed smoothly based on the capabilities of the platform.
Application can also use the MediaCodecInfo.CodecCapabilities#profileLevels to query applicable combination of profile and level for the corresponding format. Note that the requested profile/level may not be supported by the codec that is actually being used by this MediaRecorder instance.

Parameters
profile int: declared in MediaCodecInfo.CodecProfileLevel.

level int: declared in MediaCodecInfo.CodecProfileLevel.

Throws
IllegalArgumentException when an invalid profile or level value is used.

setVideoFrameRate

Added in API level 3
public void setVideoFrameRate (int rate)

Sets the frame rate of the video to be captured. Must be called after setVideoSource(). Call this after setOutputFormat() but before prepare().

NOTE: On some devices that have auto-frame rate, this sets the maximum frame rate, not a constant frame rate. Actual frame rate will vary according to lighting conditions.

Parameters
rate int: the number of frames per second of video to capture

Throws
IllegalStateException if it is called after prepare() or before setOutputFormat().

setVideoProfile

Added in API level 31
public void setVideoProfile (EncoderProfiles.VideoProfile profile)

Uses the settings from a VideoProfile object for recording.

This method should be called after the video AND audio sources are set, and before setOutputFile().

This method can be used instead of setProfile(CamcorderProfile) when using EncoderProfiles.

Parameters
profile EncoderProfiles.VideoProfile: the VideoProfile to use This value cannot be null.

setVideoSize

Added in API level 3
public void setVideoSize (int width, 
                int height)

Sets the width and height of the video to be captured. Must be called after setVideoSource(). Call this after setOutputFormat() but before prepare().

Parameters
width int: the width of the video to be captured

height int: the height of the video to be captured

Throws
IllegalStateException if it is called after prepare() or before setOutputFormat()

setVideoSource

Added in API level 3
public void setVideoSource (int video_source)

Sets the video source to be used for recording. If this method is not called, the output file will not contain an video track. The source needs to be specified before setting recording-parameters or encoders. Call this only before setOutputFormat().

Parameters
video_source int: the video source to use

Throws
IllegalStateException if it is called after setOutputFormat()

start

Added in API level 1
public void start ()

Begins capturing and encoding data to the file specified with setOutputFile(). Call this after prepare().

Since API level 13, if applications set a camera via setCamera(android.hardware.Camera), the apps can use the camera after this method call. The apps do not need to lock the camera again. However, if this method fails, the apps should still lock the camera back. The apps should not start another recording session during recording.

Throws
IllegalStateException if it is called before prepare() or when the camera is already in use by another app.

stop

Added in API level 1
public void stop ()

Stops recording. Call this after start(). Once recording is stopped, you will have to configure it again as if it has just been constructed. Note that a RuntimeException is intentionally thrown to the application, if no valid audio/video data has been received when stop() is called. This happens if stop() is called immediately after start(). The failure lets the application take action accordingly to clean up the output file (delete the output file, for instance), since the output file is not properly constructed when this happens.

Throws
IllegalStateException if it is called before start()

unregisterAudioRecordingCallback

Added in API level 29
public void unregisterAudioRecordingCallback (AudioManager.AudioRecordingCallback cb)

Unregister an audio recording callback previously registered with registerAudioRecordingCallback(java.util.concurrent.Executor, android.media.AudioManager.AudioRecordingCallback).

Parameters
cb AudioManager.AudioRecordingCallback: non-null callback to unregister

Protected methods

finalize

Added in API level 1
protected void finalize ()

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.

The general contract of finalize is that it is invoked if and when the Java virtual machine has determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, except as a result of an action taken by the finalization of some other object or class which is ready to be finalized. The finalize method may take any action, including making this object available again to other threads; the usual purpose of finalize, however, is to perform cleanup actions before the object is irrevocably discarded. For example, the finalize method for an object that represents an input/output connection might perform explicit I/O transactions to break the connection before the object is permanently discarded.

The finalize method of class Object performs no special action; it simply returns normally. Subclasses of Object may override this definition.

The Java programming language does not guarantee which thread will invoke the finalize method for any given object. It is guaranteed, however, that the thread that invokes finalize will not be holding any user-visible synchronization locks when finalize is invoked. If an uncaught exception is thrown by the finalize method, the exception is ignored and finalization of that object terminates.

After the finalize method has been invoked for an object, no further action is taken until the Java virtual machine has again determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, including possible actions by other objects or classes which are ready to be finalized, at which point the object may be discarded.

The finalize method is never invoked more than once by a Java virtual machine for any given object.

Any exception thrown by the finalize method causes the finalization of this object to be halted, but is otherwise ignored.