2 * Copyright (C) 2007 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package android.media;
19 import android.app.ActivityThread;
20 import android.hardware.Camera;
21 import android.os.Handler;
22 import android.os.Looper;
23 import android.os.Message;
24 import android.util.Log;
25 import android.view.Surface;
27 import java.io.FileDescriptor;
28 import java.io.IOException;
29 import java.io.RandomAccessFile;
30 import java.lang.ref.WeakReference;
33 * Used to record audio and video. The recording control is based on a
34 * simple state machine (see below).
36 * <p><img src="{@docRoot}images/mediarecorder_state_diagram.gif" border="0" />
39 * <p>A common case of using MediaRecorder to record audio works as follows:
41 * <pre>MediaRecorder recorder = new MediaRecorder();
42 * recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
43 * recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
44 * recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
45 * recorder.setOutputFile(PATH_NAME);
47 * recorder.start(); // Recording is now started
50 * recorder.reset(); // You can reuse the object by going back to setAudioSource() step
51 * recorder.release(); // Now the object cannot be reused
54 * <p>Applications may want to register for informational and error
55 * events in order to be informed of some internal update and possible
56 * runtime errors during recording. Registration for such events is
57 * done by setting the appropriate listeners (via calls
58 * (to {@link #setOnInfoListener(OnInfoListener)}setOnInfoListener and/or
59 * {@link #setOnErrorListener(OnErrorListener)}setOnErrorListener).
60 * In order to receive the respective callback associated with these listeners,
61 * applications are required to create MediaRecorder objects on threads with a
62 * Looper running (the main UI thread by default already has a Looper running).
64 * <p><strong>Note:</strong> Currently, MediaRecorder does not work on the emulator.
66 * <div class="special reference">
67 * <h3>Developer Guides</h3>
68 * <p>For more information about how to use MediaRecorder for recording video, read the
69 * <a href="{@docRoot}guide/topics/media/camera.html#capture-video">Camera</a> developer guide.
70 * For more information about how to use MediaRecorder for recording sound, read the
71 * <a href="{@docRoot}guide/topics/media/audio-capture.html">Audio Capture</a> developer guide.</p>
74 public class MediaRecorder
77 System.loadLibrary("media_jni");
80 private final static String TAG = "MediaRecorder";
82 // The two fields below are accessed by native methods
83 @SuppressWarnings("unused")
84 private long mNativeContext;
86 @SuppressWarnings("unused")
87 private Surface mSurface;
90 private FileDescriptor mFd;
91 private EventHandler mEventHandler;
92 private OnErrorListener mOnErrorListener;
93 private OnInfoListener mOnInfoListener;
96 * Default constructor.
98 public MediaRecorder() {
101 if ((looper = Looper.myLooper()) != null) {
102 mEventHandler = new EventHandler(this, looper);
103 } else if ((looper = Looper.getMainLooper()) != null) {
104 mEventHandler = new EventHandler(this, looper);
106 mEventHandler = null;
109 String packageName = ActivityThread.currentPackageName();
110 /* Native setup requires a weak reference to our object.
111 * It's easier to create it here than in C++.
113 native_setup(new WeakReference<MediaRecorder>(this), packageName);
117 * Sets a {@link android.hardware.Camera} to use for recording.
119 * <p>Use this function to switch quickly between preview and capture mode without a teardown of
120 * the camera object. {@link android.hardware.Camera#unlock()} should be called before
121 * this. Must call before {@link #prepare}.</p>
123 * @param c the Camera to use for recording
124 * @deprecated Use {@link #getSurface} and the {@link android.hardware.camera2} API instead.
127 public native void setCamera(Camera c);
130 * Gets the surface to record from when using SURFACE video source.
132 * <p> May only be called after {@link #prepare}. Frames rendered to the Surface before
133 * {@link #start} will be discarded.</p>
135 * @throws IllegalStateException if it is called before {@link #prepare}, after
136 * {@link #stop}, or is called when VideoSource is not set to SURFACE.
137 * @see android.media.MediaRecorder.VideoSource
139 public native Surface getSurface();
142 * Sets a Surface to show a preview of recorded media (video). Calls this
143 * before prepare() to make sure that the desirable preview display is
144 * set. If {@link #setCamera(Camera)} is used and the surface has been
145 * already set to the camera, application do not need to call this. If
146 * this is called with non-null surface, the preview surface of the camera
147 * will be replaced by the new surface. If this method is called with null
148 * surface or not called at all, media recorder will not change the preview
149 * surface of the camera.
151 * @param sv the Surface to use for the preview
152 * @see android.hardware.Camera#setPreviewDisplay(android.view.SurfaceHolder)
154 public void setPreviewDisplay(Surface sv) {
159 * Defines the audio source. These constants are used with
160 * {@link MediaRecorder#setAudioSource(int)}.
162 public final class AudioSource {
164 private AudioSource() {}
167 public final static int AUDIO_SOURCE_INVALID = -1;
169 /* Do not change these values without updating their counterparts
170 * in system/core/include/system/audio.h!
173 /** Default audio source **/
174 public static final int DEFAULT = 0;
176 /** Microphone audio source */
177 public static final int MIC = 1;
179 /** Voice call uplink (Tx) audio source */
180 public static final int VOICE_UPLINK = 2;
182 /** Voice call downlink (Rx) audio source */
183 public static final int VOICE_DOWNLINK = 3;
185 /** Voice call uplink + downlink audio source */
186 public static final int VOICE_CALL = 4;
188 /** Microphone audio source with same orientation as camera if available, the main
189 * device microphone otherwise */
190 public static final int CAMCORDER = 5;
192 /** Microphone audio source tuned for voice recognition if available, behaves like
193 * {@link #DEFAULT} otherwise. */
194 public static final int VOICE_RECOGNITION = 6;
196 /** Microphone audio source tuned for voice communications such as VoIP. It
197 * will for instance take advantage of echo cancellation or automatic gain control
198 * if available. It otherwise behaves like {@link #DEFAULT} if no voice processing
201 public static final int VOICE_COMMUNICATION = 7;
204 * Audio source for a submix of audio streams to be presented remotely.
206 * An application can use this audio source to capture a mix of audio streams
207 * that should be transmitted to a remote receiver such as a Wifi display.
208 * While recording is active, these audio streams are redirected to the remote
209 * submix instead of being played on the device speaker or headset.
211 * Certain streams are excluded from the remote submix, including
212 * {@link AudioManager#STREAM_RING}, {@link AudioManager#STREAM_ALARM},
213 * and {@link AudioManager#STREAM_NOTIFICATION}. These streams will continue
214 * to be presented locally as usual.
216 * Capturing the remote submix audio requires the
217 * {@link android.Manifest.permission#CAPTURE_AUDIO_OUTPUT} permission.
218 * This permission is reserved for use by system components and is not available to
219 * third-party applications.
222 public static final int REMOTE_SUBMIX = 8;
225 * Audio source for FM, which is used to capture current FM tuner output by FMRadio app.
226 * There are two use cases, one is for record FM stream for later listening, another is
227 * for FM indirect mode(the routing except FM to headset(headphone) device routing).
230 public static final int FM_TUNER = 1998;
233 * Audio source for preemptible, low-priority software hotword detection
234 * It presents the same gain and pre processing tuning as {@link #VOICE_RECOGNITION}.
236 * An application should use this audio source when it wishes to do
237 * always-on software hotword detection, while gracefully giving in to any other application
238 * that might want to read from the microphone.
240 * This is a hidden audio source.
243 protected static final int HOTWORD = 1999;
247 * Defines the video source. These constants are used with
248 * {@link MediaRecorder#setVideoSource(int)}.
250 public final class VideoSource {
251 /* Do not change these values without updating their counterparts
252 * in include/media/mediarecorder.h!
254 private VideoSource() {}
255 public static final int DEFAULT = 0;
256 /** Camera video source
258 * Using the {@link android.hardware.Camera} API as video source.
261 public static final int CAMERA = 1;
262 /** Surface video source
264 * Using a Surface as video source.
266 * This flag must be used when recording from an
267 * {@link android.hardware.camera2} API source.
269 * When using this video source type, use {@link MediaRecorder#getSurface()}
270 * to retrieve the surface created by MediaRecorder.
272 public static final int SURFACE = 2;
276 * Defines the output format. These constants are used with
277 * {@link MediaRecorder#setOutputFormat(int)}.
279 public final class OutputFormat {
280 /* Do not change these values without updating their counterparts
281 * in include/media/mediarecorder.h!
283 private OutputFormat() {}
284 public static final int DEFAULT = 0;
285 /** 3GPP media file format*/
286 public static final int THREE_GPP = 1;
287 /** MPEG4 media file format*/
288 public static final int MPEG_4 = 2;
290 /** The following formats are audio only .aac or .amr formats */
294 * @deprecated Deprecated in favor of MediaRecorder.OutputFormat.AMR_NB
296 public static final int RAW_AMR = 3;
298 /** AMR NB file format */
299 public static final int AMR_NB = 3;
301 /** AMR WB file format */
302 public static final int AMR_WB = 4;
304 /** @hide AAC ADIF file format */
305 public static final int AAC_ADIF = 5;
307 /** AAC ADTS file format */
308 public static final int AAC_ADTS = 6;
310 /** @hide Stream over a socket, limited to a single stream */
311 public static final int OUTPUT_FORMAT_RTP_AVP = 7;
313 /** @hide H.264/AAC data encapsulated in MPEG2/TS */
314 public static final int OUTPUT_FORMAT_MPEG2TS = 8;
316 /** VP8/VORBIS data in a WEBM container */
317 public static final int WEBM = 9;
321 * Defines the audio encoding. These constants are used with
322 * {@link MediaRecorder#setAudioEncoder(int)}.
324 public final class AudioEncoder {
325 /* Do not change these values without updating their counterparts
326 * in include/media/mediarecorder.h!
328 private AudioEncoder() {}
329 public static final int DEFAULT = 0;
330 /** AMR (Narrowband) audio codec */
331 public static final int AMR_NB = 1;
332 /** AMR (Wideband) audio codec */
333 public static final int AMR_WB = 2;
334 /** AAC Low Complexity (AAC-LC) audio codec */
335 public static final int AAC = 3;
336 /** High Efficiency AAC (HE-AAC) audio codec */
337 public static final int HE_AAC = 4;
338 /** Enhanced Low Delay AAC (AAC-ELD) audio codec */
339 public static final int AAC_ELD = 5;
340 /** Ogg Vorbis audio codec */
341 public static final int VORBIS = 6;
345 * Defines the video encoding. These constants are used with
346 * {@link MediaRecorder#setVideoEncoder(int)}.
348 public final class VideoEncoder {
349 /* Do not change these values without updating their counterparts
350 * in include/media/mediarecorder.h!
352 private VideoEncoder() {}
353 public static final int DEFAULT = 0;
354 public static final int H263 = 1;
355 public static final int H264 = 2;
356 public static final int MPEG_4_SP = 3;
357 public static final int VP8 = 4;
361 * Sets the audio source to be used for recording. If this method is not
362 * called, the output file will not contain an audio track. The source needs
363 * to be specified before setting recording-parameters or encoders. Call
364 * this only before setOutputFormat().
366 * @param audio_source the audio source to use
367 * @throws IllegalStateException if it is called after setOutputFormat()
368 * @see android.media.MediaRecorder.AudioSource
370 public native void setAudioSource(int audio_source)
371 throws IllegalStateException;
374 * Gets the maximum value for audio sources.
375 * @see android.media.MediaRecorder.AudioSource
377 public static final int getAudioSourceMax() {
378 return AudioSource.REMOTE_SUBMIX;
382 * Sets the video source to be used for recording. If this method is not
383 * called, the output file will not contain an video track. The source needs
384 * to be specified before setting recording-parameters or encoders. Call
385 * this only before setOutputFormat().
387 * @param video_source the video source to use
388 * @throws IllegalStateException if it is called after setOutputFormat()
389 * @see android.media.MediaRecorder.VideoSource
391 public native void setVideoSource(int video_source)
392 throws IllegalStateException;
395 * Uses the settings from a CamcorderProfile object for recording. This method should
396 * be called after the video AND audio sources are set, and before setOutputFile().
397 * If a time lapse CamcorderProfile is used, audio related source or recording
398 * parameters are ignored.
400 * @param profile the CamcorderProfile to use
401 * @see android.media.CamcorderProfile
403 public void setProfile(CamcorderProfile profile) {
404 setOutputFormat(profile.fileFormat);
405 setVideoFrameRate(profile.videoFrameRate);
406 setVideoSize(profile.videoFrameWidth, profile.videoFrameHeight);
407 setVideoEncodingBitRate(profile.videoBitRate);
408 setVideoEncoder(profile.videoCodec);
409 if (profile.quality >= CamcorderProfile.QUALITY_TIME_LAPSE_LOW &&
410 profile.quality <= CamcorderProfile.QUALITY_TIME_LAPSE_QVGA) {
411 // Nothing needs to be done. Call to setCaptureRate() enables
412 // time lapse video recording.
414 setAudioEncodingBitRate(profile.audioBitRate);
415 setAudioChannels(profile.audioChannels);
416 setAudioSamplingRate(profile.audioSampleRate);
417 setAudioEncoder(profile.audioCodec);
422 * Set video frame capture rate. This can be used to set a different video frame capture
423 * rate than the recorded video's playback rate. This method also sets the recording mode
424 * to time lapse. In time lapse video recording, only video is recorded. Audio related
425 * parameters are ignored when a time lapse recording session starts, if an application
428 * @param fps Rate at which frames should be captured in frames per second.
429 * The fps can go as low as desired. However the fastest fps will be limited by the hardware.
430 * For resolutions that can be captured by the video camera, the fastest fps can be computed using
431 * {@link android.hardware.Camera.Parameters#getPreviewFpsRange(int[])}. For higher
432 * resolutions the fastest fps may be more restrictive.
433 * Note that the recorder cannot guarantee that frames will be captured at the
434 * given rate due to camera/encoder limitations. However it tries to be as close as
437 public void setCaptureRate(double fps) {
438 // Make sure that time lapse is enabled when this method is called.
439 setParameter("time-lapse-enable=1");
441 double timeBetweenFrameCapture = 1 / fps;
442 long timeBetweenFrameCaptureUs = (long) (1000000 * timeBetweenFrameCapture);
443 setParameter("time-between-time-lapse-frame-capture=" + timeBetweenFrameCaptureUs);
447 * Sets the orientation hint for output video playback.
448 * This method should be called before prepare(). This method will not
449 * trigger the source video frame to rotate during video recording, but to
450 * add a composition matrix containing the rotation angle in the output
451 * video if the output format is OutputFormat.THREE_GPP or
452 * OutputFormat.MPEG_4 so that a video player can choose the proper
453 * orientation for playback. Note that some video players may choose
454 * to ignore the compostion matrix in a video during playback.
456 * @param degrees the angle to be rotated clockwise in degrees.
457 * The supported angles are 0, 90, 180, and 270 degrees.
458 * @throws IllegalArgumentException if the angle is not supported.
461 public void setOrientationHint(int degrees) {
466 throw new IllegalArgumentException("Unsupported angle: " + degrees);
468 setParameter("video-param-rotation-angle-degrees=" + degrees);
472 * Set and store the geodata (latitude and longitude) in the output file.
473 * This method should be called before prepare(). The geodata is
474 * stored in udta box if the output format is OutputFormat.THREE_GPP
475 * or OutputFormat.MPEG_4, and is ignored for other output formats.
476 * The geodata is stored according to ISO-6709 standard.
478 * @param latitude latitude in degrees. Its value must be in the
480 * @param longitude longitude in degrees. Its value must be in the
483 * @throws IllegalArgumentException if the given latitude or
484 * longitude is out of range.
487 public void setLocation(float latitude, float longitude) {
488 int latitudex10000 = (int) (latitude * 10000 + 0.5);
489 int longitudex10000 = (int) (longitude * 10000 + 0.5);
491 if (latitudex10000 > 900000 || latitudex10000 < -900000) {
492 String msg = "Latitude: " + latitude + " out of range.";
493 throw new IllegalArgumentException(msg);
495 if (longitudex10000 > 1800000 || longitudex10000 < -1800000) {
496 String msg = "Longitude: " + longitude + " out of range";
497 throw new IllegalArgumentException(msg);
500 setParameter("param-geotag-latitude=" + latitudex10000);
501 setParameter("param-geotag-longitude=" + longitudex10000);
505 * Sets the format of the output file produced during recording. Call this
506 * after setAudioSource()/setVideoSource() but before prepare().
508 * <p>It is recommended to always use 3GP format when using the H.263
509 * video encoder and AMR audio encoder. Using an MPEG-4 container format
510 * may confuse some desktop players.</p>
512 * @param output_format the output format to use. The output format
513 * needs to be specified before setting recording-parameters or encoders.
514 * @throws IllegalStateException if it is called after prepare() or before
515 * setAudioSource()/setVideoSource().
516 * @see android.media.MediaRecorder.OutputFormat
518 public native void setOutputFormat(int output_format)
519 throws IllegalStateException;
522 * Sets the width and height of the video to be captured. Must be called
523 * after setVideoSource(). Call this after setOutFormat() but before
526 * @param width the width of the video to be captured
527 * @param height the height of the video to be captured
528 * @throws IllegalStateException if it is called after
529 * prepare() or before setOutputFormat()
531 public native void setVideoSize(int width, int height)
532 throws IllegalStateException;
535 * Sets the frame rate of the video to be captured. Must be called
536 * after setVideoSource(). Call this after setOutFormat() but before
539 * @param rate the number of frames per second of video to capture
540 * @throws IllegalStateException if it is called after
541 * prepare() or before setOutputFormat().
543 * NOTE: On some devices that have auto-frame rate, this sets the
544 * maximum frame rate, not a constant frame rate. Actual frame rate
545 * will vary according to lighting conditions.
547 public native void setVideoFrameRate(int rate) throws IllegalStateException;
550 * Sets the maximum duration (in ms) of the recording session.
551 * Call this after setOutFormat() but before prepare().
552 * After recording reaches the specified duration, a notification
553 * will be sent to the {@link android.media.MediaRecorder.OnInfoListener}
554 * with a "what" code of {@link #MEDIA_RECORDER_INFO_MAX_DURATION_REACHED}
555 * and recording will be stopped. Stopping happens asynchronously, there
556 * is no guarantee that the recorder will have stopped by the time the
557 * listener is notified.
559 * @param max_duration_ms the maximum duration in ms (if zero or negative, disables the duration limit)
562 public native void setMaxDuration(int max_duration_ms) throws IllegalArgumentException;
565 * Sets the maximum filesize (in bytes) of the recording session.
566 * Call this after setOutFormat() but before prepare().
567 * After recording reaches the specified filesize, a notification
568 * will be sent to the {@link android.media.MediaRecorder.OnInfoListener}
569 * with a "what" code of {@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED}
570 * and recording will be stopped. Stopping happens asynchronously, there
571 * is no guarantee that the recorder will have stopped by the time the
572 * listener is notified.
574 * @param max_filesize_bytes the maximum filesize in bytes (if zero or negative, disables the limit)
577 public native void setMaxFileSize(long max_filesize_bytes) throws IllegalArgumentException;
580 * Sets the audio encoder to be used for recording. If this method is not
581 * called, the output file will not contain an audio track. Call this after
582 * setOutputFormat() but before prepare().
584 * @param audio_encoder the audio encoder to use.
585 * @throws IllegalStateException if it is called before
586 * setOutputFormat() or after prepare().
587 * @see android.media.MediaRecorder.AudioEncoder
589 public native void setAudioEncoder(int audio_encoder)
590 throws IllegalStateException;
593 * Sets the video encoder to be used for recording. If this method is not
594 * called, the output file will not contain an video track. Call this after
595 * setOutputFormat() and before prepare().
597 * @param video_encoder the video encoder to use.
598 * @throws IllegalStateException if it is called before
599 * setOutputFormat() or after prepare()
600 * @see android.media.MediaRecorder.VideoEncoder
602 public native void setVideoEncoder(int video_encoder)
603 throws IllegalStateException;
606 * Sets the audio sampling rate for recording. Call this method before prepare().
607 * Prepare() may perform additional checks on the parameter to make sure whether
608 * the specified audio sampling rate is applicable. The sampling rate really depends
609 * on the format for the audio recording, as well as the capabilities of the platform.
610 * For instance, the sampling rate supported by AAC audio coding standard ranges
611 * from 8 to 96 kHz, the sampling rate supported by AMRNB is 8kHz, and the sampling
612 * rate supported by AMRWB is 16kHz. Please consult with the related audio coding
613 * standard for the supported audio sampling rate.
615 * @param samplingRate the sampling rate for audio in samples per second.
617 public void setAudioSamplingRate(int samplingRate) {
618 if (samplingRate <= 0) {
619 throw new IllegalArgumentException("Audio sampling rate is not positive");
621 setParameter("audio-param-sampling-rate=" + samplingRate);
625 * Sets the number of audio channels for recording. Call this method before prepare().
626 * Prepare() may perform additional checks on the parameter to make sure whether the
627 * specified number of audio channels are applicable.
629 * @param numChannels the number of audio channels. Usually it is either 1 (mono) or 2
632 public void setAudioChannels(int numChannels) {
633 if (numChannels <= 0) {
634 throw new IllegalArgumentException("Number of channels is not positive");
636 setParameter("audio-param-number-of-channels=" + numChannels);
640 * Sets the audio encoding bit rate for recording. Call this method before prepare().
641 * Prepare() may perform additional checks on the parameter to make sure whether the
642 * specified bit rate is applicable, and sometimes the passed bitRate will be clipped
643 * internally to ensure the audio recording can proceed smoothly based on the
644 * capabilities of the platform.
646 * @param bitRate the audio encoding bit rate in bits per second.
648 public void setAudioEncodingBitRate(int bitRate) {
650 throw new IllegalArgumentException("Audio encoding bit rate is not positive");
652 setParameter("audio-param-encoding-bitrate=" + bitRate);
656 * Sets the video encoding bit rate for recording. Call this method before prepare().
657 * Prepare() may perform additional checks on the parameter to make sure whether the
658 * specified bit rate is applicable, and sometimes the passed bitRate will be
659 * clipped internally to ensure the video recording can proceed smoothly based on
660 * the capabilities of the platform.
662 * @param bitRate the video encoding bit rate in bits per second.
664 public void setVideoEncodingBitRate(int bitRate) {
666 throw new IllegalArgumentException("Video encoding bit rate is not positive");
668 setParameter("video-param-encoding-bitrate=" + bitRate);
672 * Currently not implemented. It does nothing.
673 * @deprecated Time lapse mode video recording using camera still image capture
674 * is not desirable, and will not be supported.
677 public void setAuxiliaryOutputFile(FileDescriptor fd)
679 Log.w(TAG, "setAuxiliaryOutputFile(FileDescriptor) is no longer supported.");
683 * Currently not implemented. It does nothing.
684 * @deprecated Time lapse mode video recording using camera still image capture
685 * is not desirable, and will not be supported.
688 public void setAuxiliaryOutputFile(String path)
690 Log.w(TAG, "setAuxiliaryOutputFile(String) is no longer supported.");
694 * Pass in the file descriptor of the file to be written. Call this after
695 * setOutputFormat() but before prepare().
697 * @param fd an open file descriptor to be written into.
698 * @throws IllegalStateException if it is called before
699 * setOutputFormat() or after prepare()
701 public void setOutputFile(FileDescriptor fd) throws IllegalStateException
708 * Sets the path of the output file to be produced. Call this after
709 * setOutputFormat() but before prepare().
711 * @param path The pathname to use.
712 * @throws IllegalStateException if it is called before
713 * setOutputFormat() or after prepare()
715 public void setOutputFile(String path) throws IllegalStateException
721 // native implementation
722 private native void _setOutputFile(FileDescriptor fd, long offset, long length)
723 throws IllegalStateException, IOException;
724 private native void _prepare() throws IllegalStateException, IOException;
727 * Prepares the recorder to begin capturing and encoding data. This method
728 * must be called after setting up the desired audio and video sources,
729 * encoders, file format, etc., but before start().
731 * @throws IllegalStateException if it is called after
732 * start() or before setOutputFormat().
733 * @throws IOException if prepare fails otherwise.
735 public void prepare() throws IllegalStateException, IOException
738 RandomAccessFile file = new RandomAccessFile(mPath, "rws");
740 _setOutputFile(file.getFD(), 0, 0);
744 } else if (mFd != null) {
745 _setOutputFile(mFd, 0, 0);
747 throw new IOException("No valid output file");
754 * Begins capturing and encoding data to the file specified with
755 * setOutputFile(). Call this after prepare().
757 * <p>Since API level 13, if applications set a camera via
758 * {@link #setCamera(Camera)}, the apps can use the camera after this method
759 * call. The apps do not need to lock the camera again. However, if this
760 * method fails, the apps should still lock the camera back. The apps should
761 * not start another recording session during recording.
763 * @throws IllegalStateException if it is called before
766 public native void start() throws IllegalStateException;
769 * Stops recording. Call this after start(). Once recording is stopped,
770 * you will have to configure it again as if it has just been constructed.
771 * Note that a RuntimeException is intentionally thrown to the
772 * application, if no valid audio/video data has been received when stop()
773 * is called. This happens if stop() is called immediately after
774 * start(). The failure lets the application take action accordingly to
775 * clean up the output file (delete the output file, for instance), since
776 * the output file is not properly constructed when this happens.
778 * @throws IllegalStateException if it is called before start()
780 public native void stop() throws IllegalStateException;
783 * Restarts the MediaRecorder to its idle state. After calling
784 * this method, you will have to configure it again as if it had just been
787 public void reset() {
790 // make sure none of the listeners get called anymore
791 mEventHandler.removeCallbacksAndMessages(null);
794 private native void native_reset();
797 * Returns the maximum absolute amplitude that was sampled since the last
798 * call to this method. Call this only after the setAudioSource().
800 * @return the maximum absolute amplitude measured since the last call, or
801 * 0 when called for the first time
802 * @throws IllegalStateException if it is called before
803 * the audio source has been set.
805 public native int getMaxAmplitude() throws IllegalStateException;
807 /* Do not change this value without updating its counterpart
808 * in include/media/mediarecorder.h or mediaplayer.h!
810 /** Unspecified media recorder error.
811 * @see android.media.MediaRecorder.OnErrorListener
813 public static final int MEDIA_RECORDER_ERROR_UNKNOWN = 1;
814 /** Media server died. In this case, the application must release the
815 * MediaRecorder object and instantiate a new one.
816 * @see android.media.MediaRecorder.OnErrorListener
818 public static final int MEDIA_ERROR_SERVER_DIED = 100;
821 * Interface definition for a callback to be invoked when an error
822 * occurs while recording.
824 public interface OnErrorListener
827 * Called when an error occurs while recording.
829 * @param mr the MediaRecorder that encountered the error
830 * @param what the type of error that has occurred:
832 * <li>{@link #MEDIA_RECORDER_ERROR_UNKNOWN}
833 * <li>{@link #MEDIA_ERROR_SERVER_DIED}
835 * @param extra an extra code, specific to the error type
837 void onError(MediaRecorder mr, int what, int extra);
841 * Register a callback to be invoked when an error occurs while
844 * @param l the callback that will be run
846 public void setOnErrorListener(OnErrorListener l)
848 mOnErrorListener = l;
851 /* Do not change these values without updating their counterparts
852 * in include/media/mediarecorder.h!
854 /** Unspecified media recorder error.
855 * @see android.media.MediaRecorder.OnInfoListener
857 public static final int MEDIA_RECORDER_INFO_UNKNOWN = 1;
858 /** A maximum duration had been setup and has now been reached.
859 * @see android.media.MediaRecorder.OnInfoListener
861 public static final int MEDIA_RECORDER_INFO_MAX_DURATION_REACHED = 800;
862 /** A maximum filesize had been setup and has now been reached.
863 * @see android.media.MediaRecorder.OnInfoListener
865 public static final int MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED = 801;
867 /** informational events for individual tracks, for testing purpose.
868 * The track informational event usually contains two parts in the ext1
869 * arg of the onInfo() callback: bit 31-28 contains the track id; and
870 * the rest of the 28 bits contains the informational event defined here.
871 * For example, ext1 = (1 << 28 | MEDIA_RECORDER_TRACK_INFO_TYPE) if the
872 * track id is 1 for informational event MEDIA_RECORDER_TRACK_INFO_TYPE;
873 * while ext1 = (0 << 28 | MEDIA_RECORDER_TRACK_INFO_TYPE) if the track
874 * id is 0 for informational event MEDIA_RECORDER_TRACK_INFO_TYPE. The
875 * application should extract the track id and the type of informational
876 * event from ext1, accordingly.
879 * Please update the comment for onInfo also when these
880 * events are unhidden so that application knows how to extract the track
881 * id and the informational event type from onInfo callback.
885 public static final int MEDIA_RECORDER_TRACK_INFO_LIST_START = 1000;
886 /** Signal the completion of the track for the recording session.
889 public static final int MEDIA_RECORDER_TRACK_INFO_COMPLETION_STATUS = 1000;
890 /** Indicate the recording progress in time (ms) during recording.
893 public static final int MEDIA_RECORDER_TRACK_INFO_PROGRESS_IN_TIME = 1001;
894 /** Indicate the track type: 0 for Audio and 1 for Video.
897 public static final int MEDIA_RECORDER_TRACK_INFO_TYPE = 1002;
898 /** Provide the track duration information.
901 public static final int MEDIA_RECORDER_TRACK_INFO_DURATION_MS = 1003;
902 /** Provide the max chunk duration in time (ms) for the given track.
905 public static final int MEDIA_RECORDER_TRACK_INFO_MAX_CHUNK_DUR_MS = 1004;
906 /** Provide the total number of recordd frames.
909 public static final int MEDIA_RECORDER_TRACK_INFO_ENCODED_FRAMES = 1005;
910 /** Provide the max spacing between neighboring chunks for the given track.
913 public static final int MEDIA_RECORDER_TRACK_INTER_CHUNK_TIME_MS = 1006;
914 /** Provide the elapsed time measuring from the start of the recording
915 * till the first output frame of the given track is received, excluding
916 * any intentional start time offset of a recording session for the
917 * purpose of eliminating the recording sound in the recorded file.
920 public static final int MEDIA_RECORDER_TRACK_INFO_INITIAL_DELAY_MS = 1007;
921 /** Provide the start time difference (delay) betweeen this track and
922 * the start of the movie.
925 public static final int MEDIA_RECORDER_TRACK_INFO_START_OFFSET_MS = 1008;
926 /** Provide the total number of data (in kilo-bytes) encoded.
929 public static final int MEDIA_RECORDER_TRACK_INFO_DATA_KBYTES = 1009;
933 public static final int MEDIA_RECORDER_TRACK_INFO_LIST_END = 2000;
937 * Interface definition for a callback to be invoked when an error
938 * occurs while recording.
940 public interface OnInfoListener
943 * Called when an error occurs while recording.
945 * @param mr the MediaRecorder that encountered the error
946 * @param what the type of error that has occurred:
948 * <li>{@link #MEDIA_RECORDER_INFO_UNKNOWN}
949 * <li>{@link #MEDIA_RECORDER_INFO_MAX_DURATION_REACHED}
950 * <li>{@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED}
952 * @param extra an extra code, specific to the error type
954 void onInfo(MediaRecorder mr, int what, int extra);
958 * Register a callback to be invoked when an informational event occurs while
961 * @param listener the callback that will be run
963 public void setOnInfoListener(OnInfoListener listener)
965 mOnInfoListener = listener;
968 private class EventHandler extends Handler
970 private MediaRecorder mMediaRecorder;
972 public EventHandler(MediaRecorder mr, Looper looper) {
977 /* Do not change these values without updating their counterparts
978 * in include/media/mediarecorder.h!
980 private static final int MEDIA_RECORDER_EVENT_LIST_START = 1;
981 private static final int MEDIA_RECORDER_EVENT_ERROR = 1;
982 private static final int MEDIA_RECORDER_EVENT_INFO = 2;
983 private static final int MEDIA_RECORDER_EVENT_LIST_END = 99;
985 /* Events related to individual tracks */
986 private static final int MEDIA_RECORDER_TRACK_EVENT_LIST_START = 100;
987 private static final int MEDIA_RECORDER_TRACK_EVENT_ERROR = 100;
988 private static final int MEDIA_RECORDER_TRACK_EVENT_INFO = 101;
989 private static final int MEDIA_RECORDER_TRACK_EVENT_LIST_END = 1000;
993 public void handleMessage(Message msg) {
994 if (mMediaRecorder.mNativeContext == 0) {
995 Log.w(TAG, "mediarecorder went away with unhandled events");
999 case MEDIA_RECORDER_EVENT_ERROR:
1000 case MEDIA_RECORDER_TRACK_EVENT_ERROR:
1001 if (mOnErrorListener != null)
1002 mOnErrorListener.onError(mMediaRecorder, msg.arg1, msg.arg2);
1006 case MEDIA_RECORDER_EVENT_INFO:
1007 case MEDIA_RECORDER_TRACK_EVENT_INFO:
1008 if (mOnInfoListener != null)
1009 mOnInfoListener.onInfo(mMediaRecorder, msg.arg1, msg.arg2);
1014 Log.e(TAG, "Unknown message type " + msg.what);
1021 * Called from native code when an interesting event happens. This method
1022 * just uses the EventHandler system to post the event back to the main app thread.
1023 * We use a weak reference to the original MediaRecorder object so that the native
1024 * code is safe from the object disappearing from underneath it. (This is
1025 * the cookie passed to native_setup().)
1027 private static void postEventFromNative(Object mediarecorder_ref,
1028 int what, int arg1, int arg2, Object obj)
1030 MediaRecorder mr = (MediaRecorder)((WeakReference)mediarecorder_ref).get();
1035 if (mr.mEventHandler != null) {
1036 Message m = mr.mEventHandler.obtainMessage(what, arg1, arg2, obj);
1037 mr.mEventHandler.sendMessage(m);
1042 * Releases resources associated with this MediaRecorder object.
1043 * It is good practice to call this method when you're done
1044 * using the MediaRecorder. In particular, whenever an Activity
1045 * of an application is paused (its onPause() method is called),
1046 * or stopped (its onStop() method is called), this method should be
1047 * invoked to release the MediaRecorder object, unless the application
1048 * has a special need to keep the object around. In addition to
1049 * unnecessary resources (such as memory and instances of codecs)
1050 * being held, failure to call this method immediately if a
1051 * MediaRecorder object is no longer needed may also lead to
1052 * continuous battery consumption for mobile devices, and recording
1053 * failure for other applications if no multiple instances of the
1054 * same codec are supported on a device. Even if multiple instances
1055 * of the same codec are supported, some performance degradation
1056 * may be expected when unnecessary multiple instances are used
1059 public native void release();
1061 private static native final void native_init();
1063 private native final void native_setup(Object mediarecorder_this,
1064 String clientName) throws IllegalStateException;
1066 private native final void native_finalize();
1068 private native void setParameter(String nameValuePair);
1071 protected void finalize() { native_finalize(); }