IT. Expert System.

Android Reference

MediaRecorder


android.media

Class MediaRecorder



  • public class MediaRecorder
    extends Object
    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.

    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.

    • Field Detail

      • MEDIA_RECORDER_TRACK_INFO_LIST_START

        public static final int MEDIA_RECORDER_TRACK_INFO_LIST_START
        informational events for individual tracks, for testing purpose. The track informational event usually contains two parts in the ext1 arg of the onInfo() callback: bit 31-28 contains the track id; and the rest of the 28 bits contains the informational event defined here. For example, ext1 = (1 << 28 | media_recorder_track_info_type) if the track id is 1 for informational event media_recorder_track_info_type; while ext1 = (0 << 28 | media_recorder_track_info_type) if the track id is 0 for informational event media_recorder_track_info_type. the application should extract the track id and the type of informational event from ext1, accordingly. fixme: please update the comment for oninfo also when these events are unhidden so that application knows how to extract the track id and the informational event type from oninfo callback.
        See Also:
        Constant Field Values
      • MEDIA_RECORDER_TRACK_INFO_COMPLETION_STATUS

        public static final int MEDIA_RECORDER_TRACK_INFO_COMPLETION_STATUS
        Signal the completion of the track for the recording session.
        See Also:
        Constant Field Values
      • MEDIA_RECORDER_TRACK_INFO_PROGRESS_IN_TIME

        public static final int MEDIA_RECORDER_TRACK_INFO_PROGRESS_IN_TIME
        Indicate the recording progress in time (ms) during recording.
        See Also:
        Constant Field Values
      • MEDIA_RECORDER_TRACK_INFO_TYPE

        public static final int MEDIA_RECORDER_TRACK_INFO_TYPE
        Indicate the track type: 0 for Audio and 1 for Video.
        See Also:
        Constant Field Values
      • MEDIA_RECORDER_TRACK_INFO_DURATION_MS

        public static final int MEDIA_RECORDER_TRACK_INFO_DURATION_MS
        Provide the track duration information.
        See Also:
        Constant Field Values
      • MEDIA_RECORDER_TRACK_INFO_MAX_CHUNK_DUR_MS

        public static final int MEDIA_RECORDER_TRACK_INFO_MAX_CHUNK_DUR_MS
        Provide the max chunk duration in time (ms) for the given track.
        See Also:
        Constant Field Values
      • MEDIA_RECORDER_TRACK_INFO_ENCODED_FRAMES

        public static final int MEDIA_RECORDER_TRACK_INFO_ENCODED_FRAMES
        Provide the total number of recordd frames.
        See Also:
        Constant Field Values
      • MEDIA_RECORDER_TRACK_INTER_CHUNK_TIME_MS

        public static final int MEDIA_RECORDER_TRACK_INTER_CHUNK_TIME_MS
        Provide the max spacing between neighboring chunks for the given track.
        See Also:
        Constant Field Values
      • MEDIA_RECORDER_TRACK_INFO_INITIAL_DELAY_MS

        public static final int MEDIA_RECORDER_TRACK_INFO_INITIAL_DELAY_MS
        Provide the elapsed time measuring from the start of the recording till the first output frame of the given track is received, excluding any intentional start time offset of a recording session for the purpose of eliminating the recording sound in the recorded file.
        See Also:
        Constant Field Values
      • MEDIA_RECORDER_TRACK_INFO_START_OFFSET_MS

        public static final int MEDIA_RECORDER_TRACK_INFO_START_OFFSET_MS
        Provide the start time difference (delay) betweeen this track and the start of the movie.
        See Also:
        Constant Field Values
      • MEDIA_RECORDER_TRACK_INFO_DATA_KBYTES

        public static final int MEDIA_RECORDER_TRACK_INFO_DATA_KBYTES
        Provide the total number of data (in kilo-bytes) encoded.
        See Also:
        Constant Field Values
      • MEDIA_RECORDER_TRACK_INFO_LIST_END

        public static final int MEDIA_RECORDER_TRACK_INFO_LIST_END
        See Also:
        Constant Field Values
    • Constructor Detail

      • MediaRecorder

        public MediaRecorder()
        Default constructor.
    • Method Detail

      • setCamera

        public void setCamera(Camera c)
        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 - the Camera to use for recording
      • setPreviewDisplay

        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(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 - the Surface to use for the preview
        See Also:
        Camera.setPreviewDisplay(android.view.SurfaceHolder)
      • setAudioSource

        public void setAudioSource(int audio_source)
                            throws IllegalStateException
        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 - the audio source to use
        Throws:
        IllegalStateException - if it is called after setOutputFormat()
        See Also:
        MediaRecorder.AudioSource
      • getAudioSourceMax

        public static final int getAudioSourceMax()
        Gets the maximum value for audio sources.
        See Also:
        MediaRecorder.AudioSource
      • setVideoSource

        public void setVideoSource(int video_source)
                            throws IllegalStateException
        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 - the video source to use
        Throws:
        IllegalStateException - if it is called after setOutputFormat()
        See Also:
        MediaRecorder.VideoSource
      • setProfile

        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 - the CamcorderProfile to use
        See Also:
        CamcorderProfile
      • setCaptureRate

        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 - 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.
      • setOrientationHint

        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 - 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.
      • setLocation

        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 - latitude in degrees. Its value must be in the range [-90, 90].
        longitude - longitude in degrees. Its value must be in the range [-180, 180].
        Throws:
        IllegalArgumentException - if the given latitude or longitude is out of range.
      • setOutputFormat

        public void setOutputFormat(int output_format)
                             throws IllegalStateException
        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 - 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:
        MediaRecorder.OutputFormat
      • setVideoSize

        public void setVideoSize(int width,
                        int height)
                          throws IllegalStateException
        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 - the width of the video to be captured
        height - the height of the video to be captured
        Throws:
        IllegalStateException - if it is called after prepare() or before setOutputFormat()
      • setVideoFrameRate

        public void setVideoFrameRate(int rate)
                               throws IllegalStateException
        Sets the frame rate of the video to be captured. Must be called after setVideoSource(). Call this after setOutFormat() but before prepare().
        Parameters:
        rate - 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.
      • setMaxDuration

        public void setMaxDuration(int max_duration_ms)
                            throws IllegalArgumentException
        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 - the maximum duration in ms (if zero or negative, disables the duration limit)
        Throws:
        IllegalArgumentException
      • setMaxFileSize

        public void setMaxFileSize(long max_filesize_bytes)
                            throws IllegalArgumentException
        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 - the maximum filesize in bytes (if zero or negative, disables the limit)
        Throws:
        IllegalArgumentException
      • setAudioEncoder

        public void setAudioEncoder(int audio_encoder)
                             throws IllegalStateException
        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 - the audio encoder to use.
        Throws:
        IllegalStateException - if it is called before setOutputFormat() or after prepare().
        See Also:
        MediaRecorder.AudioEncoder
      • setVideoEncoder

        public void setVideoEncoder(int video_encoder)
                             throws IllegalStateException
        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 - the video encoder to use.
        Throws:
        IllegalStateException - if it is called before setOutputFormat() or after prepare()
        See Also:
        MediaRecorder.VideoEncoder
      • setAudioSamplingRate

        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 - the sampling rate for audio in samples per second.
      • setAudioChannels

        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 - the number of audio channels. Usually it is either 1 (mono) or 2 (stereo).
      • setAudioEncodingBitRate

        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 - the audio encoding bit rate in bits per second.
      • setVideoEncodingBitRate

        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.
        Parameters:
        bitRate - the video encoding bit rate in bits per second.
      • setAuxiliaryOutputFile

        public void setAuxiliaryOutputFile(FileDescriptor fd)
        Deprecated. Time lapse mode video recording using camera still image capture is not desirable, and will not be supported.
        Currently not implemented. It does nothing.
      • setAuxiliaryOutputFile

        public void setAuxiliaryOutputFile(String path)
        Deprecated. Time lapse mode video recording using camera still image capture is not desirable, and will not be supported.
        Currently not implemented. It does nothing.
      • setOutputFile

        public void setOutputFile(FileDescriptor fd)
                           throws IllegalStateException
        Pass in the file descriptor of the file to be written. Call this after setOutputFormat() but before prepare().
        Parameters:
        fd - an open file descriptor to be written into.
        Throws:
        IllegalStateException - if it is called before setOutputFormat() or after prepare()
      • setOutputFile

        public void setOutputFile(String path)
                           throws IllegalStateException
        Sets the path of the output file to be produced. Call this after setOutputFormat() but before prepare().
        Parameters:
        path - The pathname to use.
        Throws:
        IllegalStateException - if it is called before setOutputFormat() or after prepare()
      • prepare

        public void prepare()
                     throws IllegalStateException,
                            IOException
        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.
      • start

        public void start()
                   throws IllegalStateException
        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().
      • stop

        public void stop()
                  throws IllegalStateException
        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()
      • reset

        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.
      • getMaxAmplitude

        public int getMaxAmplitude()
                            throws IllegalStateException
        Returns the maximum absolute amplitude that was sampled since the last call to this method. Call this only after the setAudioSource().
        Returns:
        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.
      • setOnErrorListener

        public void setOnErrorListener(MediaRecorder.OnErrorListener l)
        Register a callback to be invoked when an error occurs while recording.
        Parameters:
        l - the callback that will be run
      • setOnInfoListener

        public void setOnInfoListener(MediaRecorder.OnInfoListener listener)
        Register a callback to be invoked when an informational event occurs while recording.
        Parameters:
        listener - the callback that will be run
      • release

        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.
      • finalize

        protected void finalize()
        Description copied from class: Object
        Invoked when the garbage collector has detected that this instance is no longer reachable. The default implementation does nothing, but this method can be overridden to free resources.

        Note that objects that override finalize are significantly more expensive than objects that don't. Finalizers may be run a long time after the object is no longer reachable, depending on memory pressure, so it's a bad idea to rely on them for cleanup. Note also that finalizers are run on a single VM-wide finalizer thread, so doing blocking work in a finalizer is a bad idea. A finalizer is usually only necessary for a class that has a native peer and needs to call a native method to destroy that peer. Even then, it's better to provide an explicit close method (and implement Closeable), and insist that callers manually dispose of instances. This works well for something like files, but less well for something like a BigInteger where typical calling code would have to deal with lots of temporaries. Unfortunately, code that creates lots of temporaries is the worst kind of code from the point of view of the single finalizer thread.

        If you must use finalizers, consider at least providing your own ReferenceQueue and having your own thread process that queue.

        Unlike constructors, finalizers are not automatically chained. You are responsible for calling super.finalize() yourself.

        Uncaught exceptions thrown by finalizers are ignored and do not terminate the finalizer thread. See Effective Java Item 7, "Avoid finalizers" for more.

        Overrides:
        finalize in class Object


Content

Android Reference

Java basics

Java Enterprise Edition (EE)

Java Standard Edition (SE)

SQL

HTML

PHP

CSS

Java Script

MYSQL

JQUERY

VBS

REGEX

C

C++

C#

Design patterns

RFC (standard status)

RFC (proposed standard status)

RFC (draft standard status)

RFC (informational status)

RFC (experimental status)

RFC (best current practice status)

RFC (historic status)

RFC (unknown status)

IT dictionary

License.
All information of this service is derived from the free sources and is provided solely in the form of quotations. This service provides information and interfaces solely for the familiarization (not ownership) and under the "as is" condition.
Copyright 2016 © ELTASK.COM. All rights reserved.
Site is optimized for mobile devices.
Downloads: 2434 / . Delta: 0.05885 с