public
class
MediaRecorder
extends Object
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(OnInfoListener)
setOnInfoListener and/or
setOnErrorListener(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.
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.
Nested classes | |
---|---|
class |
MediaRecorder.AudioEncoder
Defines the audio encoding. |
class |
MediaRecorder.AudioSource
Defines the audio source. |
interface |
MediaRecorder.OnErrorListener
Interface definition for a callback to be invoked when an error occurs while recording. |
interface |
MediaRecorder.OnInfoListener
Interface definition for a callback to be invoked when an error occurs while 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_REACHED
A maximum filesize had been setup and has now been reached. |
int |
MEDIA_RECORDER_INFO_UNKNOWN
Unspecified media recorder error. |
Public constructors | |
---|---|
MediaRecorder()
Default constructor. |
Public methods | |
---|---|
static
final
int
|
getAudioSourceMax()
Gets the maximum value for audio sources. |
int
|
getMaxAmplitude()
Returns the maximum absolute amplitude that was sampled since the last call to this method. |
Surface
|
getSurface()
Gets the surface to record from when using SURFACE video source. |
void
|
pause()
Pauses recording. |
void
|
prepare()
Prepares the recorder to begin capturing and encoding data. |
void
|
release()
Releases resources associated with this MediaRecorder object. |
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
|
setAudioSamplingRate(int samplingRate)
Sets the audio sampling rate for recording. |
void
|
setAudioSource(int audio_source)
Sets the audio source to be used for recording. |
void
|
setCamera(Camera c)
This method was deprecated
in API level 21.
Use |
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
|
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
|
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(String path)
Sets the path of the output file to be produced. |
void
|
setOutputFile(FileDescriptor fd)
Pass in the file descriptor of the file to be written. |
void
|
setOutputFormat(int output_format)
Sets the format of the output file produced during recording. |
void
|
setPreviewDisplay(Surface sv)
Sets a Surface to show a preview of recorded media (video). |
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
|
setVideoFrameRate(int rate)
Sets the frame rate of the video to be captured. |
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. |
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 | |
---|---|
From
class
java.lang.Object
|
int MEDIA_ERROR_SERVER_DIED
Media server died. In this case, the application must release the MediaRecorder object and instantiate a new one.
See also:
Constant Value: 100 (0x00000064)
int MEDIA_RECORDER_ERROR_UNKNOWN
Unspecified media recorder error.
See also:
Constant Value: 1 (0x00000001)
int MEDIA_RECORDER_INFO_MAX_DURATION_REACHED
A maximum duration had been setup and has now been reached.
See also:
Constant Value: 800 (0x00000320)
int MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED
A maximum filesize had been setup and has now been reached.
See also:
Constant Value: 801 (0x00000321)
int MEDIA_RECORDER_INFO_UNKNOWN
Unspecified media recorder error.
See also:
Constant Value: 1 (0x00000001)
int getAudioSourceMax ()
Gets the maximum value for audio sources.
Returns | |
---|---|
int |
See also:
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. |
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. |
See also:
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() |
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. |
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.
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.
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:
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).
|
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. |
Throws | |
---|---|
IllegalStateException |
if it is called before setOutputFormat() or after prepare(). |
See also:
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.
|
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.
|
void setAudioSource (int audio_source)
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 | |
---|---|
audio_source |
int :
the audio source to use |
Throws | |
---|---|
IllegalStateException |
if it is called after setOutputFormat() |
See also:
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. unlock()
should be called before
this. Must call before prepare()
.
Parameters | |
---|---|
c |
Camera :
the Camera to use for recording |
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
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.
|
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
createPersistentInputSurface() |
Throws | |
---|---|
IllegalStateException |
if it is called after prepare() and before
stop() . |
IllegalArgumentException |
if the surface was not created by
createPersistentInputSurface() . |
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. |
void setMaxDuration (int max_duration_ms)
Sets the maximum duration (in ms) of the recording session.
Call this after setOutFormat() 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.
Parameters | |
---|---|
max_duration_ms |
int :
the maximum duration in ms (if zero or negative, disables the duration limit)
|
Throws | |
---|---|
IllegalArgumentException |
void setMaxFileSize (long max_filesize_bytes)
Sets the maximum filesize (in bytes) of the recording session.
Call this after setOutFormat() 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.
Parameters | |
---|---|
max_filesize_bytes |
long :
the maximum filesize in bytes (if zero or negative, disables the limit)
|
Throws | |
---|---|
IllegalArgumentException |
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
|
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
|
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. |
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() |
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() |
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. |
Throws | |
---|---|
IllegalStateException |
if it is called after prepare() or before setAudioSource()/setVideoSource(). |
See also:
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(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 |
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:
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. |
Throws | |
---|---|
IllegalStateException |
if it is called before setOutputFormat() or after prepare() |
See also:
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.
Parameters | |
---|---|
bitRate |
int :
the video encoding bit rate in bits per second.
|
void setVideoFrameRate (int rate)
Sets the frame rate of the video to be captured. Must be called after setVideoSource(). Call this after setOutFormat() but before prepare().
Parameters | |
---|---|
rate |
int :
the number of frames per second of video to capture |
Throws | |
---|---|
IllegalStateException |
if it is called after prepare() or before setOutputFormat(). 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. |
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 setOutFormat() 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() |
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() |
See also:
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(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(). |
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() |
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 JavaTM 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.