MediaRecorder
open class MediaRecorder : AudioRecordingMonitor, AudioRouting, MicrophoneDirection
kotlin.Any | |
↳ | 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(context); 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.
Summary
Nested classes | |
---|---|
Defines the audio encoding. |
|
Defines the audio source. |
|
abstract |
Interface definition for a callback to be invoked when an error occurs while recording. |
abstract |
Interface definition of a callback to be invoked to communicate some info and/or warning about the recording. |
Defines the output format. |
|
Defines the video encoding. |
|
Defines the video source. |
Constants | |
---|---|
static Int |
Media server died. |
static Int |
Unspecified media recorder error. |
static Int |
A maximum duration had been setup and has now been reached. |
static Int |
A maximum filesize had been setup and current recorded file size has reached 90% of the limit. |
static Int |
A maximum filesize had been setup and has now been reached. |
static Int |
A maximum filesize had been reached and MediaRecorder has switched output to a new file set by application #setNextOutputFile. |
static Int |
Unspecified media recorder info. |
Inherited constants | |
---|---|
Public constructors | |
---|---|
Default constructor. |
|
MediaRecorder(context: Context) Default constructor. |
Public methods | |
---|---|
open Unit |
addOnRoutingChangedListener(listener: AudioRouting.OnRoutingChangedListener!, handler: Handler!) Adds an |
open MutableList<MicrophoneInfo!>! |
Return A lists of |
open AudioRecordingConfiguration? |
Returns the current active audio recording for this audio recorder. |
static Int |
Gets the maximum value for audio sources. |
open LogSessionId |
Returns the |
open Int |
Returns the maximum absolute amplitude that was sampled since the last call to this method. |
open PersistableBundle! |
Return Metrics data about the current Mediarecorder instance. |
open AudioDeviceInfo! |
Returns the selected input device specified by |
open AudioDeviceInfo! |
Returns an |
open Surface! |
Gets the surface to record from when using SURFACE video source. |
open Boolean |
Returns whether this MediaRecorder is marked as privacy sensitive or not with regard to audio capture. |
open Unit |
pause() Pauses recording. |
open Unit |
prepare() Prepares the recorder to begin capturing and encoding data. |
open Unit |
Register a callback to be notified of audio capture changes via a |
open Unit |
release() Releases resources associated with this MediaRecorder object. |
open Unit |
Removes an |
open Unit |
reset() Restarts the MediaRecorder to its idle state. |
open Unit |
resume() Resumes recording. |
open Unit |
setAudioChannels(numChannels: Int) Sets the number of audio channels for recording. |
open Unit |
setAudioEncoder(audio_encoder: Int) Sets the audio encoder to be used for recording. |
open Unit |
setAudioEncodingBitRate(bitRate: Int) Sets the audio encoding bit rate for recording. |
open Unit |
setAudioProfile(profile: EncoderProfiles.AudioProfile) Uses the settings from an AudioProfile for recording. |
open Unit |
setAudioSamplingRate(samplingRate: Int) Sets the audio sampling rate for recording. |
open Unit |
setAudioSource(audioSource: Int) Sets the audio source to be used for recording. |
open Unit |
Sets a |
open Unit |
setCaptureRate(fps: Double) Set video frame capture rate. |
open Unit |
setInputSurface(surface: Surface) Configures the recorder to use a persistent surface when using SURFACE video source. |
open Unit |
setLocation(latitude: Float, longitude: Float) Set and store the geodata (latitude and longitude) in the output file. |
open Unit |
Sets the |
open Unit |
setMaxDuration(max_duration_ms: Int) Sets the maximum duration (in ms) of the recording session. |
open Unit |
setMaxFileSize(max_filesize_bytes: Long) Sets the maximum filesize (in bytes) of the recording session. |
open Unit |
setNextOutputFile(file: File!) Sets the next output file to be used when the maximum filesize is reached on the prior output #setOutputFile or #setNextOutputFile). |
open Unit |
Sets the next output file descriptor to be used when the maximum filesize is reached on the prior output #setOutputFile or #setNextOutputFile). |
open Unit |
Register a callback to be invoked when an error occurs while recording. |
open Unit |
setOnInfoListener(listener: MediaRecorder.OnInfoListener!) Register a callback to be invoked when an informational event occurs while recording. |
open Unit |
setOrientationHint(degrees: Int) Sets the orientation hint for output video playback. |
open Unit |
setOutputFile(file: File!) Pass in the file object to be written. |
open Unit |
setOutputFile(fd: FileDescriptor!) Pass in the file descriptor of the file to be written. |
open Unit |
setOutputFile(path: String!) Sets the path of the output file to be produced. |
open Unit |
setOutputFormat(output_format: Int) Sets the format of the output file produced during recording. |
open Boolean |
setPreferredDevice(deviceInfo: AudioDeviceInfo!) Specifies an audio device (via an |
open Boolean |
setPreferredMicrophoneDirection(direction: Int) Specifies the logical microphone (for processing). |
open Boolean |
Specifies the zoom factor (i.e. the field dimension) for the selected microphone (for processing). |
open Unit |
setPreviewDisplay(sv: Surface!) Sets a Surface to show a preview of recorded media (video). |
open Unit |
setPrivacySensitive(privacySensitive: Boolean) Indicates that this capture request is privacy sensitive and that any concurrent capture is not permitted. |
open Unit |
setProfile(profile: CamcorderProfile!) Uses the settings from a CamcorderProfile object for recording. |
open Unit |
setVideoEncoder(video_encoder: Int) Sets the video encoder to be used for recording. |
open Unit |
setVideoEncodingBitRate(bitRate: Int) Sets the video encoding bit rate for recording. |
open Unit |
setVideoEncodingProfileLevel(profile: Int, level: Int) Sets the desired video encoding profile and level for recording. |
open Unit |
setVideoFrameRate(rate: Int) Sets the frame rate of the video to be captured. |
open Unit |
setVideoProfile(profile: EncoderProfiles.VideoProfile) Uses the settings from a VideoProfile object for recording. |
open Unit |
setVideoSize(width: Int, height: Int) Sets the width and height of the video to be captured. |
open Unit |
setVideoSource(video_source: Int) Sets the video source to be used for recording. |
open Unit |
start() Begins capturing and encoding data to the file specified with setOutputFile(). |
open Unit |
stop() Stops recording. |
open Unit |
Unregister an audio recording callback previously registered with |
Protected methods | |
---|---|
open Unit |
finalize() |
Constants
MEDIA_ERROR_SERVER_DIED
static val MEDIA_ERROR_SERVER_DIED: Int
Media server died. In this case, the application must release the MediaRecorder object and instantiate a new one.
Value: 100
MEDIA_RECORDER_ERROR_UNKNOWN
static val MEDIA_RECORDER_ERROR_UNKNOWN: Int
Unspecified media recorder error.
Value: 1
MEDIA_RECORDER_INFO_MAX_DURATION_REACHED
static val MEDIA_RECORDER_INFO_MAX_DURATION_REACHED: Int
A maximum duration had been setup and has now been reached.
Value: 800
MEDIA_RECORDER_INFO_MAX_FILESIZE_APPROACHING
static val MEDIA_RECORDER_INFO_MAX_FILESIZE_APPROACHING: Int
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 to set the next output file. Otherwise, recording will stop when reaching maximum file size.
Value: 802
MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED
static val MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED: Int
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.
Value: 801
MEDIA_RECORDER_INFO_NEXT_OUTPUT_FILE_STARTED
static val MEDIA_RECORDER_INFO_NEXT_OUTPUT_FILE_STARTED: Int
A maximum filesize had been reached and MediaRecorder has switched output to a new file set by application #setNextOutputFile. For best practice, application should use this event to keep track of whether the file previously set has been used or not.
Value: 803
MEDIA_RECORDER_INFO_UNKNOWN
static val MEDIA_RECORDER_INFO_UNKNOWN: Int
Unspecified media recorder info.
Value: 1
Public constructors
MediaRecorder
MediaRecorder()
Deprecated: Use MediaRecorder(android.content.Context)
instead
Default constructor.
MediaRecorder
MediaRecorder(context: Context)
Default constructor.
Parameters | |
---|---|
context |
Context: Context the recorder belongs to This value cannot be null . |
Public methods
addOnRoutingChangedListener
open fun addOnRoutingChangedListener(
listener: AudioRouting.OnRoutingChangedListener!,
handler: Handler!
): Unit
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
open fun getActiveMicrophones(): MutableList<MicrophoneInfo!>!
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.
Return | |
---|---|
MutableList<MicrophoneInfo!>! |
a lists of MicrophoneInfo representing the active microphones |
Exceptions | |
---|---|
java.io.IOException |
if an error occurs |
getActiveRecordingConfiguration
open fun getActiveRecordingConfiguration(): AudioRecordingConfiguration?
Returns the current active audio recording for this audio recorder.
Return | |
---|---|
AudioRecordingConfiguration? |
a valid AudioRecordingConfiguration if this recorder is active or null otherwise. |
getAudioSourceMax
static fun getAudioSourceMax(): Int
Gets the maximum value for audio sources.
getLogSessionId
open fun getLogSessionId(): LogSessionId
Returns the LogSessionId
for MediaRecorder.
Return | |
---|---|
LogSessionId |
the global ID for monitoring the MediaRecorder performance This value cannot be null . |
getMaxAmplitude
open fun getMaxAmplitude(): Int
Returns the maximum absolute amplitude that was sampled since the last call to this method. Call this only after the setAudioSource().
Return | |
---|---|
Int |
the maximum absolute amplitude measured since the last call, or 0 when called for the first time |
Exceptions | |
---|---|
java.lang.IllegalStateException |
if it is called before the audio source has been set. |
getMetrics
open fun getMetrics(): PersistableBundle!
Return Metrics data about the current Mediarecorder instance.
Return | |
---|---|
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
open fun getPreferredDevice(): AudioDeviceInfo!
Returns the selected input device specified by setPreferredDevice
. Note that this is not guaranteed to correspond to the actual device being used for recording.
getRoutedDevice
open fun getRoutedDevice(): AudioDeviceInfo!
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.
getSurface
open fun getSurface(): Surface!
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.
Exceptions | |
---|---|
java.lang.IllegalStateException |
if it is called before prepare , after stop , or is called when VideoSource is not set to SURFACE. |
isPrivacySensitive
open fun isPrivacySensitive(): Boolean
Returns whether this MediaRecorder is marked as privacy sensitive or not with regard to audio capture.
See setPrivacySensitive(boolean)
Return | |
---|---|
Boolean |
true if privacy sensitive, false otherwise |
pause
open fun pause(): Unit
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.
Exceptions | |
---|---|
java.lang.IllegalStateException |
if it is called before start() or after stop() |
prepare
open fun prepare(): Unit
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().
Exceptions | |
---|---|
java.lang.IllegalStateException |
if it is called after start() or before setOutputFormat(). |
java.io.IOException |
if prepare fails otherwise. |
registerAudioRecordingCallback
open fun registerAudioRecordingCallback(
executor: Executor,
cb: AudioManager.AudioRecordingCallback
): Unit
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
open fun release(): Unit
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
open fun removeOnRoutingChangedListener(listener: AudioRouting.OnRoutingChangedListener!): Unit
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
open fun reset(): Unit
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
open fun resume(): Unit
Resumes recording. Call this after start(). It does nothing if the recording is not paused.
Exceptions | |
---|---|
java.lang.IllegalStateException |
if it is called before start() or after stop() |
See Also
setAudioChannels
open fun setAudioChannels(numChannels: Int): Unit
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
open fun setAudioEncoder(audio_encoder: Int): Unit
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().
Exceptions | |
---|---|
java.lang.IllegalStateException |
if it is called before setOutputFormat() or after prepare(). |
setAudioEncodingBitRate
open fun setAudioEncodingBitRate(bitRate: Int): Unit
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
open fun setAudioProfile(profile: EncoderProfiles.AudioProfile): Unit
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
when using EncoderProfiles.
Parameters | |
---|---|
profile |
EncoderProfiles.AudioProfile: the AudioProfile to use This value cannot be null . |
setAudioSamplingRate
open fun setAudioSamplingRate(samplingRate: Int): Unit
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
open fun setAudioSource(audioSource: Int): Unit
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().
Exceptions | |
---|---|
java.lang.IllegalStateException |
if it is called after setOutputFormat() |
setCamera
open funsetCamera(c: Camera!): Unit
Deprecated: Use getSurface
and the android.hardware.camera2
API instead.
Sets a android.hardware.Camera
to use for recording.
Use this function to switch quickly between preview and capture mode without a teardown of the camera object. android.hardware.Camera#unlock()
should be called before this. Must call before prepare
.
Parameters | |
---|---|
c |
Camera!: the Camera to use for recording |
setCaptureRate
open fun setCaptureRate(fps: Double): Unit
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 android.hardware.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
open fun setInputSurface(surface: Surface): Unit
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 . |
Exceptions | |
---|---|
java.lang.IllegalStateException |
if it is called after prepare and before stop . |
java.lang.IllegalArgumentException |
if the surface was not created by MediaCodec.createPersistentInputSurface . |
setLocation
open fun setLocation(
latitude: Float,
longitude: Float
): Unit
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]. |
Exceptions | |
---|---|
java.lang.IllegalArgumentException |
if the given latitude or longitude is out of range. |
setLogSessionId
open fun setLogSessionId(id: LogSessionId): Unit
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
open fun setMaxDuration(max_duration_ms: Int): Unit
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 android.media.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) |
setMaxFileSize
open fun setMaxFileSize(max_filesize_bytes: Long): Unit
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 android.media.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) |
setNextOutputFile
open fun setNextOutputFile(file: File!): Unit
Sets the next output file to be used when the maximum filesize is reached on the prior output #setOutputFile or #setNextOutputFile). 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 android.media.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. |
Exceptions | |
---|---|
java.lang.IllegalStateException |
if it is called before prepare(). |
java.io.IOException |
if setNextOutputFile fails otherwise. |
setNextOutputFile
open fun setNextOutputFile(fd: FileDescriptor!): Unit
Sets the next output file descriptor to be used when the maximum filesize is reached on the prior output #setOutputFile or #setNextOutputFile). 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 android.media.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. |
Exceptions | |
---|---|
java.lang.IllegalStateException |
if it is called before prepare(). |
java.io.IOException |
if setNextOutputFile fails otherwise. |
setOnErrorListener
open fun setOnErrorListener(l: MediaRecorder.OnErrorListener!): Unit
Register a callback to be invoked when an error occurs while recording.
Parameters | |
---|---|
l |
MediaRecorder.OnErrorListener!: the callback that will be run |
setOnInfoListener
open fun setOnInfoListener(listener: MediaRecorder.OnInfoListener!): Unit
Register a callback to be invoked when an informational event occurs while recording.
Parameters | |
---|---|
listener |
MediaRecorder.OnInfoListener!: the callback that will be run |
setOrientationHint
open fun setOrientationHint(degrees: Int): Unit
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. |
Exceptions | |
---|---|
java.lang.IllegalArgumentException |
if the angle is not supported. |
setOutputFile
open fun setOutputFile(file: File!): Unit
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. |
setOutputFile
open fun setOutputFile(fd: FileDescriptor!): Unit
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. |
Exceptions | |
---|---|
java.lang.IllegalStateException |
if it is called before setOutputFormat() or after prepare() |
setOutputFile
open fun setOutputFile(path: String!): Unit
Sets the path of the output file to be produced. Call this after setOutputFormat() but before prepare().
Parameters | |
---|---|
path |
String!: The pathname to use. |
Exceptions | |
---|---|
java.lang.IllegalStateException |
if it is called before setOutputFormat() or after prepare() |
setOutputFormat
open fun setOutputFormat(output_format: Int): Unit
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 android.media.MediaRecorder.OutputFormat#DEFAULT , android.media.MediaRecorder.OutputFormat#THREE_GPP , android.media.MediaRecorder.OutputFormat#MPEG_4 , android.media.MediaRecorder.OutputFormat#AMR_NB , android.media.MediaRecorder.OutputFormat#AMR_WB , android.media.MediaRecorder.OutputFormat.AAC_ADIF, android.media.MediaRecorder.OutputFormat#AAC_ADTS , android.media.MediaRecorder.OutputFormat#MPEG_2_TS , android.media.MediaRecorder.OutputFormat#WEBM , android.media.MediaRecorder.OutputFormat.HEIF, or android.media.MediaRecorder.OutputFormat#OGG |
Exceptions | |
---|---|
java.lang.IllegalStateException |
if it is called after prepare() or before setAudioSource()/setVideoSource(). |
setPreferredDevice
open fun setPreferredDevice(deviceInfo: AudioDeviceInfo!): Boolean
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. |
Return | |
---|---|
Boolean |
true if succesful, false if the specified AudioDeviceInfo is non-null and does not correspond to a valid audio input device. |
setPreferredMicrophoneDirection
open fun setPreferredMicrophoneDirection(direction: Int): Boolean
Specifies the logical microphone (for processing).
Parameters | |
---|---|
direction |
Int: Direction constant. Value is android.media.MicrophoneDirection#MIC_DIRECTION_UNSPECIFIED , android.media.MicrophoneDirection#MIC_DIRECTION_TOWARDS_USER , android.media.MicrophoneDirection#MIC_DIRECTION_AWAY_FROM_USER , or android.media.MicrophoneDirection#MIC_DIRECTION_EXTERNAL |
Return | |
---|---|
Boolean |
true if sucessful. |
setPreferredMicrophoneFieldDimension
open fun setPreferredMicrophoneFieldDimension(zoom: Float): Boolean
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 |
Return | |
---|---|
Boolean |
true if sucessful. |
setPreviewDisplay
open fun setPreviewDisplay(sv: Surface!): Unit
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
open fun setPrivacySensitive(privacySensitive: Boolean): Unit
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:
AudioSource.MIC
AudioSource.CAMCORDER
AudioSource.VOICE_RECOGNITION
AudioSource.VOICE_COMMUNICATION
AudioSource.UNPROCESSED
AudioSource.VOICE_PERFORMANCE
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. |
Exceptions | |
---|---|
java.lang.IllegalStateException |
if called before setAudioSource(int) or after setOutputFormat(int) |
setProfile
open fun setProfile(profile: CamcorderProfile!): Unit
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
open fun setVideoEncoder(video_encoder: Int): Unit
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().
Exceptions | |
---|---|
java.lang.IllegalStateException |
if it is called before setOutputFormat() or after prepare() |
setVideoEncodingBitRate
open fun setVideoEncodingBitRate(bitRate: Int): Unit
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 android.os.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
open fun setVideoEncodingProfileLevel(
profile: Int,
level: Int
): Unit
Sets the desired video encoding profile and level for recording. The profile and level must be valid for the video encoder set by setVideoEncoder
. This method can called before or after setVideoEncoder
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 . |
Exceptions | |
---|---|
java.lang.IllegalArgumentException |
when an invalid profile or level value is used. |
setVideoFrameRate
open fun setVideoFrameRate(rate: Int): Unit
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 |
Exceptions | |
---|---|
java.lang.IllegalStateException |
if it is called after prepare() or before setOutputFormat(). |
setVideoProfile
open fun setVideoProfile(profile: EncoderProfiles.VideoProfile): Unit
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
when using EncoderProfiles.
Parameters | |
---|---|
profile |
EncoderProfiles.VideoProfile: the VideoProfile to use This value cannot be null . |
setVideoSize
open fun setVideoSize(
width: Int,
height: Int
): Unit
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 |
Exceptions | |
---|---|
java.lang.IllegalStateException |
if it is called after prepare() or before setOutputFormat() |
setVideoSource
open fun setVideoSource(video_source: Int): Unit
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 |
Exceptions | |
---|---|
java.lang.IllegalStateException |
if it is called after setOutputFormat() |
start
open fun start(): Unit
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.
Exceptions | |
---|---|
java.lang.IllegalStateException |
if it is called before prepare() or when the camera is already in use by another app. |
stop
open fun stop(): Unit
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.
Exceptions | |
---|---|
java.lang.IllegalStateException |
if it is called before start() |
unregisterAudioRecordingCallback
open fun unregisterAudioRecordingCallback(cb: AudioManager.AudioRecordingCallback): Unit
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
protected open fun finalize(): Unit
Exceptions | |
---|---|
java.lang.Throwable |
the Exception raised by this method |