MediaRecorder.java revision 6644a826a12babfb88aadc65c29e8bf3d4d8c1d3
1/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
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
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17package android.media;
18
19import android.hardware.Camera;
20import android.os.Handler;
21import android.os.Looper;
22import android.os.Message;
23import android.util.Log;
24import android.view.Surface;
25
26import java.io.FileDescriptor;
27import java.io.FileOutputStream;
28import java.io.IOException;
29import java.lang.ref.WeakReference;
30
31/**
32 * Used to record audio and video. The recording control is based on a
33 * simple state machine (see below).
34 *
35 * <p><img src="{@docRoot}images/mediarecorder_state_diagram.gif" border="0" />
36 * </p>
37 *
38 * <p>A common case of using MediaRecorder to record audio works as follows:
39 *
40 * <pre>MediaRecorder recorder = new MediaRecorder();
41 * recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
42 * recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
43 * recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
44 * recorder.setOutputFile(PATH_NAME);
45 * recorder.prepare();
46 * recorder.start();   // Recording is now started
47 * ...
48 * recorder.stop();
49 * recorder.reset();   // You can reuse the object by going back to setAudioSource() step
50 * recorder.release(); // Now the object cannot be reused
51 * </pre>
52 *
53 * <p>Applications may want to register for informational and error
54 * events in order to be informed of some internal update and possible
55 * runtime errors during recording. Registration for such events is
56 * done by setting the appropriate listeners (via calls
57 * (to {@link #setOnInfoListener(OnInfoListener)}setOnInfoListener and/or
58 * {@link #setOnErrorListener(OnErrorListener)}setOnErrorListener).
59 * In order to receive the respective callback associated with these listeners,
60 * applications are required to create MediaRecorder objects on threads with a
61 * Looper running (the main UI thread by default already has a Looper running).
62 *
63 * <p><strong>Note:</strong> Currently, MediaRecorder does not work on the emulator.
64 *
65 * <div class="special reference">
66 * <h3>Developer Guides</h3>
67 * <p>For more information about how to use MediaRecorder for recording video, read the
68 * <a href="{@docRoot}guide/topics/media/camera.html#capture-video">Camera</a> developer guide.
69 * For more information about how to use MediaRecorder for recording sound, read the
70 * <a href="{@docRoot}guide/topics/media/audio-capture.html">Audio Capture</a> developer guide.</p>
71 * </div>
72 */
73public class MediaRecorder
74{
75    static {
76        System.loadLibrary("media_jni");
77        native_init();
78    }
79    private final static String TAG = "MediaRecorder";
80
81    // The two fields below are accessed by native methods
82    @SuppressWarnings("unused")
83    private int mNativeContext;
84
85    @SuppressWarnings("unused")
86    private Surface mSurface;
87
88    private String mPath;
89    private FileDescriptor mFd;
90    private EventHandler mEventHandler;
91    private OnErrorListener mOnErrorListener;
92    private OnInfoListener mOnInfoListener;
93
94    /**
95     * Default constructor.
96     */
97    public MediaRecorder() {
98
99        Looper looper;
100        if ((looper = Looper.myLooper()) != null) {
101            mEventHandler = new EventHandler(this, looper);
102        } else if ((looper = Looper.getMainLooper()) != null) {
103            mEventHandler = new EventHandler(this, looper);
104        } else {
105            mEventHandler = null;
106        }
107
108        /* Native setup requires a weak reference to our object.
109         * It's easier to create it here than in C++.
110         */
111        native_setup(new WeakReference<MediaRecorder>(this));
112    }
113
114    /**
115     * Sets a Camera to use for recording. Use this function to switch
116     * quickly between preview and capture mode without a teardown of
117     * the camera object. {@link android.hardware.Camera#unlock()} should be
118     * called before this. Must call before prepare().
119     *
120     * @param c the Camera to use for recording
121     */
122    public native void setCamera(Camera c);
123
124    /**
125     * Sets a Surface to show a preview of recorded media (video). Calls this
126     * before prepare() to make sure that the desirable preview display is
127     * set. If {@link #setCamera(Camera)} is used and the surface has been
128     * already set to the camera, application do not need to call this. If
129     * this is called with non-null surface, the preview surface of the camera
130     * will be replaced by the new surface. If this method is called with null
131     * surface or not called at all, media recorder will not change the preview
132     * surface of the camera.
133     *
134     * @param sv the Surface to use for the preview
135     * @see android.hardware.Camera#setPreviewDisplay(android.view.SurfaceHolder)
136     */
137    public void setPreviewDisplay(Surface sv) {
138        mSurface = sv;
139    }
140
141    /**
142     * Defines the audio source. These constants are used with
143     * {@link MediaRecorder#setAudioSource(int)}.
144     */
145    public final class AudioSource {
146      /* Do not change these values without updating their counterparts
147       * in system/core/include/system/audio.h!
148       */
149        private AudioSource() {}
150
151        /** Default audio source **/
152        public static final int DEFAULT = 0;
153
154        /** Microphone audio source */
155        public static final int MIC = 1;
156
157        /** Voice call uplink (Tx) audio source */
158        public static final int VOICE_UPLINK = 2;
159
160        /** Voice call downlink (Rx) audio source */
161        public static final int VOICE_DOWNLINK = 3;
162
163        /** Voice call uplink + downlink audio source */
164        public static final int VOICE_CALL = 4;
165
166        /** Microphone audio source with same orientation as camera if available, the main
167         *  device microphone otherwise */
168        public static final int CAMCORDER = 5;
169
170        /** Microphone audio source tuned for voice recognition if available, behaves like
171         *  {@link #DEFAULT} otherwise. */
172        public static final int VOICE_RECOGNITION = 6;
173
174        /** Microphone audio source tuned for voice communications such as VoIP. It
175         *  will for instance take advantage of echo cancellation or automatic gain control
176         *  if available. It otherwise behaves like {@link #DEFAULT} if no voice processing
177         *  is applied.
178         */
179        public static final int VOICE_COMMUNICATION = 7;
180    }
181
182    /**
183     * Defines the video source. These constants are used with
184     * {@link MediaRecorder#setVideoSource(int)}.
185     */
186    public final class VideoSource {
187      /* Do not change these values without updating their counterparts
188       * in include/media/mediarecorder.h!
189       */
190        private VideoSource() {}
191        public static final int DEFAULT = 0;
192        /** Camera video source */
193        public static final int CAMERA = 1;
194        /** @hide */
195        public static final int GRALLOC_BUFFER = 2;
196    }
197
198    /**
199     * Defines the output format. These constants are used with
200     * {@link MediaRecorder#setOutputFormat(int)}.
201     */
202    public final class OutputFormat {
203      /* Do not change these values without updating their counterparts
204       * in include/media/mediarecorder.h!
205       */
206        private OutputFormat() {}
207        public static final int DEFAULT = 0;
208        /** 3GPP media file format*/
209        public static final int THREE_GPP = 1;
210        /** MPEG4 media file format*/
211        public static final int MPEG_4 = 2;
212
213        /** The following formats are audio only .aac or .amr formats */
214
215        /**
216         * AMR NB file format
217         * @deprecated  Deprecated in favor of MediaRecorder.OutputFormat.AMR_NB
218         */
219        public static final int RAW_AMR = 3;
220
221        /** AMR NB file format */
222        public static final int AMR_NB = 3;
223
224        /** AMR WB file format */
225        public static final int AMR_WB = 4;
226
227        /** @hide AAC ADIF file format */
228        public static final int AAC_ADIF = 5;
229
230        /** AAC ADTS file format */
231        public static final int AAC_ADTS = 6;
232
233        /** @hide Stream over a socket, limited to a single stream */
234        public static final int OUTPUT_FORMAT_RTP_AVP = 7;
235
236        /** @hide H.264/AAC data encapsulated in MPEG2/TS */
237        public static final int OUTPUT_FORMAT_MPEG2TS = 8;
238    };
239
240    /**
241     * Defines the audio encoding. These constants are used with
242     * {@link MediaRecorder#setAudioEncoder(int)}.
243     */
244    public final class AudioEncoder {
245      /* Do not change these values without updating their counterparts
246       * in include/media/mediarecorder.h!
247       */
248        private AudioEncoder() {}
249        public static final int DEFAULT = 0;
250        /** AMR (Narrowband) audio codec */
251        public static final int AMR_NB = 1;
252        /** AMR (Wideband) audio codec */
253        public static final int AMR_WB = 2;
254        /** AAC audio codec */
255        public static final int AAC = 3;
256        /** @hide enhanced AAC audio codec */
257        public static final int AAC_PLUS = 4;
258        /** @hide enhanced AAC plus audio codec */
259        public static final int EAAC_PLUS = 5;
260        /** AAC-ELD audio codec */
261        public static final int AAC_ELD = 6;
262    }
263
264    /**
265     * Defines the video encoding. These constants are used with
266     * {@link MediaRecorder#setVideoEncoder(int)}.
267     */
268    public final class VideoEncoder {
269      /* Do not change these values without updating their counterparts
270       * in include/media/mediarecorder.h!
271       */
272        private VideoEncoder() {}
273        public static final int DEFAULT = 0;
274        public static final int H263 = 1;
275        public static final int H264 = 2;
276        public static final int MPEG_4_SP = 3;
277    }
278
279    /**
280     * Sets the audio source to be used for recording. If this method is not
281     * called, the output file will not contain an audio track. The source needs
282     * to be specified before setting recording-parameters or encoders. Call
283     * this only before setOutputFormat().
284     *
285     * @param audio_source the audio source to use
286     * @throws IllegalStateException if it is called after setOutputFormat()
287     * @see android.media.MediaRecorder.AudioSource
288     */
289    public native void setAudioSource(int audio_source)
290            throws IllegalStateException;
291
292    /**
293     * Gets the maximum value for audio sources.
294     * @see android.media.MediaRecorder.AudioSource
295     */
296    public static final int getAudioSourceMax() { return AudioSource.VOICE_COMMUNICATION; }
297
298    /**
299     * Sets the video source to be used for recording. If this method is not
300     * called, the output file will not contain an video track. The source needs
301     * to be specified before setting recording-parameters or encoders. Call
302     * this only before setOutputFormat().
303     *
304     * @param video_source the video source to use
305     * @throws IllegalStateException if it is called after setOutputFormat()
306     * @see android.media.MediaRecorder.VideoSource
307     */
308    public native void setVideoSource(int video_source)
309            throws IllegalStateException;
310
311    /**
312     * Uses the settings from a CamcorderProfile object for recording. This method should
313     * be called after the video AND audio sources are set, and before setOutputFile().
314     * If a time lapse CamcorderProfile is used, audio related source or recording
315     * parameters are ignored.
316     *
317     * @param profile the CamcorderProfile to use
318     * @see android.media.CamcorderProfile
319     */
320    public void setProfile(CamcorderProfile profile) {
321        setOutputFormat(profile.fileFormat);
322        setVideoFrameRate(profile.videoFrameRate);
323        setVideoSize(profile.videoFrameWidth, profile.videoFrameHeight);
324        setVideoEncodingBitRate(profile.videoBitRate);
325        setVideoEncoder(profile.videoCodec);
326        if (profile.quality >= CamcorderProfile.QUALITY_TIME_LAPSE_LOW &&
327             profile.quality <= CamcorderProfile.QUALITY_TIME_LAPSE_QVGA) {
328            // Nothing needs to be done. Call to setCaptureRate() enables
329            // time lapse video recording.
330        } else {
331            setAudioEncodingBitRate(profile.audioBitRate);
332            setAudioChannels(profile.audioChannels);
333            setAudioSamplingRate(profile.audioSampleRate);
334            setAudioEncoder(profile.audioCodec);
335        }
336    }
337
338    /**
339     * Set video frame capture rate. This can be used to set a different video frame capture
340     * rate than the recorded video's playback rate. This method also sets the recording mode
341     * to time lapse. In time lapse video recording, only video is recorded. Audio related
342     * parameters are ignored when a time lapse recording session starts, if an application
343     * sets them.
344     *
345     * @param fps Rate at which frames should be captured in frames per second.
346     * The fps can go as low as desired. However the fastest fps will be limited by the hardware.
347     * For resolutions that can be captured by the video camera, the fastest fps can be computed using
348     * {@link android.hardware.Camera.Parameters#getPreviewFpsRange(int[])}. For higher
349     * resolutions the fastest fps may be more restrictive.
350     * Note that the recorder cannot guarantee that frames will be captured at the
351     * given rate due to camera/encoder limitations. However it tries to be as close as
352     * possible.
353     */
354    public void setCaptureRate(double fps) {
355        // Make sure that time lapse is enabled when this method is called.
356        setParameter(String.format("time-lapse-enable=1"));
357
358        double timeBetweenFrameCapture = 1 / fps;
359        int timeBetweenFrameCaptureMs = (int) (1000 * timeBetweenFrameCapture);
360        setParameter(String.format("time-between-time-lapse-frame-capture=%d",
361                    timeBetweenFrameCaptureMs));
362    }
363
364    /**
365     * Sets the orientation hint for output video playback.
366     * This method should be called before prepare(). This method will not
367     * trigger the source video frame to rotate during video recording, but to
368     * add a composition matrix containing the rotation angle in the output
369     * video if the output format is OutputFormat.THREE_GPP or
370     * OutputFormat.MPEG_4 so that a video player can choose the proper
371     * orientation for playback. Note that some video players may choose
372     * to ignore the compostion matrix in a video during playback.
373     *
374     * @param degrees the angle to be rotated clockwise in degrees.
375     * The supported angles are 0, 90, 180, and 270 degrees.
376     * @throws IllegalArgumentException if the angle is not supported.
377     *
378     */
379    public void setOrientationHint(int degrees) {
380        if (degrees != 0   &&
381            degrees != 90  &&
382            degrees != 180 &&
383            degrees != 270) {
384            throw new IllegalArgumentException("Unsupported angle: " + degrees);
385        }
386        setParameter("video-param-rotation-angle-degrees=" + degrees);
387    }
388
389    /**
390     * Set and store the geodata (latitude and longitude) in the output file.
391     * This method should be called before prepare(). The geodata is
392     * stored in udta box if the output format is OutputFormat.THREE_GPP
393     * or OutputFormat.MPEG_4, and is ignored for other output formats.
394     * The geodata is stored according to ISO-6709 standard.
395     *
396     * @param latitude latitude in degrees. Its value must be in the
397     * range [-90, 90].
398     * @param longitude longitude in degrees. Its value must be in the
399     * range [-180, 180].
400     *
401     * @throws IllegalArgumentException if the given latitude or
402     * longitude is out of range.
403     *
404     */
405    public void setLocation(float latitude, float longitude) {
406        int latitudex10000  = (int) (latitude * 10000 + 0.5);
407        int longitudex10000 = (int) (longitude * 10000 + 0.5);
408
409        if (latitudex10000 > 900000 || latitudex10000 < -900000) {
410            String msg = "Latitude: " + latitude + " out of range.";
411            throw new IllegalArgumentException(msg);
412        }
413        if (longitudex10000 > 1800000 || longitudex10000 < -1800000) {
414            String msg = "Longitude: " + longitude + " out of range";
415            throw new IllegalArgumentException(msg);
416        }
417
418        setParameter("param-geotag-latitude=" + latitudex10000);
419        setParameter("param-geotag-longitude=" + longitudex10000);
420    }
421
422    /**
423     * Sets the format of the output file produced during recording. Call this
424     * after setAudioSource()/setVideoSource() but before prepare().
425     *
426     * <p>It is recommended to always use 3GP format when using the H.263
427     * video encoder and AMR audio encoder. Using an MPEG-4 container format
428     * may confuse some desktop players.</p>
429     *
430     * @param output_format the output format to use. The output format
431     * needs to be specified before setting recording-parameters or encoders.
432     * @throws IllegalStateException if it is called after prepare() or before
433     * setAudioSource()/setVideoSource().
434     * @see android.media.MediaRecorder.OutputFormat
435     */
436    public native void setOutputFormat(int output_format)
437            throws IllegalStateException;
438
439    /**
440     * Sets the width and height of the video to be captured.  Must be called
441     * after setVideoSource(). Call this after setOutFormat() but before
442     * prepare().
443     *
444     * @param width the width of the video to be captured
445     * @param height the height of the video to be captured
446     * @throws IllegalStateException if it is called after
447     * prepare() or before setOutputFormat()
448     */
449    public native void setVideoSize(int width, int height)
450            throws IllegalStateException;
451
452    /**
453     * Sets the frame rate of the video to be captured.  Must be called
454     * after setVideoSource(). Call this after setOutFormat() but before
455     * prepare().
456     *
457     * @param rate the number of frames per second of video to capture
458     * @throws IllegalStateException if it is called after
459     * prepare() or before setOutputFormat().
460     *
461     * NOTE: On some devices that have auto-frame rate, this sets the
462     * maximum frame rate, not a constant frame rate. Actual frame rate
463     * will vary according to lighting conditions.
464     */
465    public native void setVideoFrameRate(int rate) throws IllegalStateException;
466
467    /**
468     * Sets the maximum duration (in ms) of the recording session.
469     * Call this after setOutFormat() but before prepare().
470     * After recording reaches the specified duration, a notification
471     * will be sent to the {@link android.media.MediaRecorder.OnInfoListener}
472     * with a "what" code of {@link #MEDIA_RECORDER_INFO_MAX_DURATION_REACHED}
473     * and recording will be stopped. Stopping happens asynchronously, there
474     * is no guarantee that the recorder will have stopped by the time the
475     * listener is notified.
476     *
477     * @param max_duration_ms the maximum duration in ms (if zero or negative, disables the duration limit)
478     *
479     */
480    public native void setMaxDuration(int max_duration_ms) throws IllegalArgumentException;
481
482    /**
483     * Sets the maximum filesize (in bytes) of the recording session.
484     * Call this after setOutFormat() but before prepare().
485     * After recording reaches the specified filesize, a notification
486     * will be sent to the {@link android.media.MediaRecorder.OnInfoListener}
487     * with a "what" code of {@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED}
488     * and recording will be stopped. Stopping happens asynchronously, there
489     * is no guarantee that the recorder will have stopped by the time the
490     * listener is notified.
491     *
492     * @param max_filesize_bytes the maximum filesize in bytes (if zero or negative, disables the limit)
493     *
494     */
495    public native void setMaxFileSize(long max_filesize_bytes) throws IllegalArgumentException;
496
497    /**
498     * Sets the audio encoder to be used for recording. If this method is not
499     * called, the output file will not contain an audio track. Call this after
500     * setOutputFormat() but before prepare().
501     *
502     * @param audio_encoder the audio encoder to use.
503     * @throws IllegalStateException if it is called before
504     * setOutputFormat() or after prepare().
505     * @see android.media.MediaRecorder.AudioEncoder
506     */
507    public native void setAudioEncoder(int audio_encoder)
508            throws IllegalStateException;
509
510    /**
511     * Sets the video encoder to be used for recording. If this method is not
512     * called, the output file will not contain an video track. Call this after
513     * setOutputFormat() and before prepare().
514     *
515     * @param video_encoder the video encoder to use.
516     * @throws IllegalStateException if it is called before
517     * setOutputFormat() or after prepare()
518     * @see android.media.MediaRecorder.VideoEncoder
519     */
520    public native void setVideoEncoder(int video_encoder)
521            throws IllegalStateException;
522
523    /**
524     * Sets the audio sampling rate for recording. Call this method before prepare().
525     * Prepare() may perform additional checks on the parameter to make sure whether
526     * the specified audio sampling rate is applicable. The sampling rate really depends
527     * on the format for the audio recording, as well as the capabilities of the platform.
528     * For instance, the sampling rate supported by AAC audio coding standard ranges
529     * from 8 to 96 kHz, the sampling rate supported by AMRNB is 8kHz, and the sampling
530     * rate supported by AMRWB is 16kHz. Please consult with the related audio coding
531     * standard for the supported audio sampling rate.
532     *
533     * @param samplingRate the sampling rate for audio in samples per second.
534     */
535    public void setAudioSamplingRate(int samplingRate) {
536        if (samplingRate <= 0) {
537            throw new IllegalArgumentException("Audio sampling rate is not positive");
538        }
539        setParameter("audio-param-sampling-rate=" + samplingRate);
540    }
541
542    /**
543     * Sets the number of audio channels for recording. Call this method before prepare().
544     * Prepare() may perform additional checks on the parameter to make sure whether the
545     * specified number of audio channels are applicable.
546     *
547     * @param numChannels the number of audio channels. Usually it is either 1 (mono) or 2
548     * (stereo).
549     */
550    public void setAudioChannels(int numChannels) {
551        if (numChannels <= 0) {
552            throw new IllegalArgumentException("Number of channels is not positive");
553        }
554        setParameter("audio-param-number-of-channels=" + numChannels);
555    }
556
557    /**
558     * Sets the audio encoding bit rate for recording. Call this method before prepare().
559     * Prepare() may perform additional checks on the parameter to make sure whether the
560     * specified bit rate is applicable, and sometimes the passed bitRate will be clipped
561     * internally to ensure the audio recording can proceed smoothly based on the
562     * capabilities of the platform.
563     *
564     * @param bitRate the audio encoding bit rate in bits per second.
565     */
566    public void setAudioEncodingBitRate(int bitRate) {
567        if (bitRate <= 0) {
568            throw new IllegalArgumentException("Audio encoding bit rate is not positive");
569        }
570        setParameter("audio-param-encoding-bitrate=" + bitRate);
571    }
572
573    /**
574     * Sets the video encoding bit rate for recording. Call this method before prepare().
575     * Prepare() may perform additional checks on the parameter to make sure whether the
576     * specified bit rate is applicable, and sometimes the passed bitRate will be
577     * clipped internally to ensure the video recording can proceed smoothly based on
578     * the capabilities of the platform.
579     *
580     * @param bitRate the video encoding bit rate in bits per second.
581     */
582    public void setVideoEncodingBitRate(int bitRate) {
583        if (bitRate <= 0) {
584            throw new IllegalArgumentException("Video encoding bit rate is not positive");
585        }
586        setParameter("video-param-encoding-bitrate=" + bitRate);
587    }
588
589    /**
590     * Currently not implemented. It does nothing.
591     * @deprecated Time lapse mode video recording using camera still image capture
592     * is not desirable, and will not be supported.
593     * @hide
594     */
595    public void setAuxiliaryOutputFile(FileDescriptor fd)
596    {
597        Log.w(TAG, "setAuxiliaryOutputFile(FileDescriptor) is no longer supported.");
598    }
599
600    /**
601     * Currently not implemented. It does nothing.
602     * @deprecated Time lapse mode video recording using camera still image capture
603     * is not desirable, and will not be supported.
604     * @hide
605     */
606    public void setAuxiliaryOutputFile(String path)
607    {
608        Log.w(TAG, "setAuxiliaryOutputFile(String) is no longer supported.");
609    }
610
611    /**
612     * Pass in the file descriptor of the file to be written. Call this after
613     * setOutputFormat() but before prepare().
614     *
615     * @param fd an open file descriptor to be written into.
616     * @throws IllegalStateException if it is called before
617     * setOutputFormat() or after prepare()
618     */
619    public void setOutputFile(FileDescriptor fd) throws IllegalStateException
620    {
621        mPath = null;
622        mFd = fd;
623    }
624
625    /**
626     * Sets the path of the output file to be produced. Call this after
627     * setOutputFormat() but before prepare().
628     *
629     * @param path The pathname to use.
630     * @throws IllegalStateException if it is called before
631     * setOutputFormat() or after prepare()
632     */
633    public void setOutputFile(String path) throws IllegalStateException
634    {
635        mFd = null;
636        mPath = path;
637    }
638
639    // native implementation
640    private native void _setOutputFile(FileDescriptor fd, long offset, long length)
641        throws IllegalStateException, IOException;
642    private native void _prepare() throws IllegalStateException, IOException;
643
644    /**
645     * Prepares the recorder to begin capturing and encoding data. This method
646     * must be called after setting up the desired audio and video sources,
647     * encoders, file format, etc., but before start().
648     *
649     * @throws IllegalStateException if it is called after
650     * start() or before setOutputFormat().
651     * @throws IOException if prepare fails otherwise.
652     */
653    public void prepare() throws IllegalStateException, IOException
654    {
655        if (mPath != null) {
656            FileOutputStream fos = new FileOutputStream(mPath);
657            try {
658                _setOutputFile(fos.getFD(), 0, 0);
659            } finally {
660                fos.close();
661            }
662        } else if (mFd != null) {
663            _setOutputFile(mFd, 0, 0);
664        } else {
665            throw new IOException("No valid output file");
666        }
667
668        _prepare();
669    }
670
671    /**
672     * Begins capturing and encoding data to the file specified with
673     * setOutputFile(). Call this after prepare().
674     *
675     * <p>Since API level 13, if applications set a camera via
676     * {@link #setCamera(Camera)}, the apps can use the camera after this method
677     * call. The apps do not need to lock the camera again. However, if this
678     * method fails, the apps should still lock the camera back. The apps should
679     * not start another recording session during recording.
680     *
681     * @throws IllegalStateException if it is called before
682     * prepare().
683     */
684    public native void start() throws IllegalStateException;
685
686    /**
687     * Stops recording. Call this after start(). Once recording is stopped,
688     * you will have to configure it again as if it has just been constructed.
689     * Note that a RuntimeException is intentionally thrown to the
690     * application, if no valid audio/video data has been received when stop()
691     * is called. This happens if stop() is called immediately after
692     * start(). The failure lets the application take action accordingly to
693     * clean up the output file (delete the output file, for instance), since
694     * the output file is not properly constructed when this happens.
695     *
696     * @throws IllegalStateException if it is called before start()
697     */
698    public native void stop() throws IllegalStateException;
699
700    /**
701     * Restarts the MediaRecorder to its idle state. After calling
702     * this method, you will have to configure it again as if it had just been
703     * constructed.
704     */
705    public void reset() {
706        native_reset();
707
708        // make sure none of the listeners get called anymore
709        mEventHandler.removeCallbacksAndMessages(null);
710    }
711
712    private native void native_reset();
713
714    /**
715     * Returns the maximum absolute amplitude that was sampled since the last
716     * call to this method. Call this only after the setAudioSource().
717     *
718     * @return the maximum absolute amplitude measured since the last call, or
719     * 0 when called for the first time
720     * @throws IllegalStateException if it is called before
721     * the audio source has been set.
722     */
723    public native int getMaxAmplitude() throws IllegalStateException;
724
725    /* Do not change this value without updating its counterpart
726     * in include/media/mediarecorder.h!
727     */
728    /** Unspecified media recorder error.
729     * @see android.media.MediaRecorder.OnErrorListener
730     */
731    public static final int MEDIA_RECORDER_ERROR_UNKNOWN = 1;
732
733    /**
734     * Interface definition for a callback to be invoked when an error
735     * occurs while recording.
736     */
737    public interface OnErrorListener
738    {
739        /**
740         * Called when an error occurs while recording.
741         *
742         * @param mr the MediaRecorder that encountered the error
743         * @param what    the type of error that has occurred:
744         * <ul>
745         * <li>{@link #MEDIA_RECORDER_ERROR_UNKNOWN}
746         * </ul>
747         * @param extra   an extra code, specific to the error type
748         */
749        void onError(MediaRecorder mr, int what, int extra);
750    }
751
752    /**
753     * Register a callback to be invoked when an error occurs while
754     * recording.
755     *
756     * @param l the callback that will be run
757     */
758    public void setOnErrorListener(OnErrorListener l)
759    {
760        mOnErrorListener = l;
761    }
762
763    /* Do not change these values without updating their counterparts
764     * in include/media/mediarecorder.h!
765     */
766    /** Unspecified media recorder error.
767     * @see android.media.MediaRecorder.OnInfoListener
768     */
769    public static final int MEDIA_RECORDER_INFO_UNKNOWN              = 1;
770    /** A maximum duration had been setup and has now been reached.
771     * @see android.media.MediaRecorder.OnInfoListener
772     */
773    public static final int MEDIA_RECORDER_INFO_MAX_DURATION_REACHED = 800;
774    /** A maximum filesize had been setup and has now been reached.
775     * @see android.media.MediaRecorder.OnInfoListener
776     */
777    public static final int MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED = 801;
778
779    /** informational events for individual tracks, for testing purpose.
780     * The track informational event usually contains two parts in the ext1
781     * arg of the onInfo() callback: bit 31-28 contains the track id; and
782     * the rest of the 28 bits contains the informational event defined here.
783     * For example, ext1 = (1 << 28 | MEDIA_RECORDER_TRACK_INFO_TYPE) if the
784     * track id is 1 for informational event MEDIA_RECORDER_TRACK_INFO_TYPE;
785     * while ext1 = (0 << 28 | MEDIA_RECORDER_TRACK_INFO_TYPE) if the track
786     * id is 0 for informational event MEDIA_RECORDER_TRACK_INFO_TYPE. The
787     * application should extract the track id and the type of informational
788     * event from ext1, accordingly.
789     *
790     * FIXME:
791     * Please update the comment for onInfo also when these
792     * events are unhidden so that application knows how to extract the track
793     * id and the informational event type from onInfo callback.
794     *
795     * {@hide}
796     */
797    public static final int MEDIA_RECORDER_TRACK_INFO_LIST_START        = 1000;
798    /** Signal the completion of the track for the recording session.
799     * {@hide}
800     */
801    public static final int MEDIA_RECORDER_TRACK_INFO_COMPLETION_STATUS = 1000;
802    /** Indicate the recording progress in time (ms) during recording.
803     * {@hide}
804     */
805    public static final int MEDIA_RECORDER_TRACK_INFO_PROGRESS_IN_TIME  = 1001;
806    /** Indicate the track type: 0 for Audio and 1 for Video.
807     * {@hide}
808     */
809    public static final int MEDIA_RECORDER_TRACK_INFO_TYPE              = 1002;
810    /** Provide the track duration information.
811     * {@hide}
812     */
813    public static final int MEDIA_RECORDER_TRACK_INFO_DURATION_MS       = 1003;
814    /** Provide the max chunk duration in time (ms) for the given track.
815     * {@hide}
816     */
817    public static final int MEDIA_RECORDER_TRACK_INFO_MAX_CHUNK_DUR_MS  = 1004;
818    /** Provide the total number of recordd frames.
819     * {@hide}
820     */
821    public static final int MEDIA_RECORDER_TRACK_INFO_ENCODED_FRAMES    = 1005;
822    /** Provide the max spacing between neighboring chunks for the given track.
823     * {@hide}
824     */
825    public static final int MEDIA_RECORDER_TRACK_INTER_CHUNK_TIME_MS    = 1006;
826    /** Provide the elapsed time measuring from the start of the recording
827     * till the first output frame of the given track is received, excluding
828     * any intentional start time offset of a recording session for the
829     * purpose of eliminating the recording sound in the recorded file.
830     * {@hide}
831     */
832    public static final int MEDIA_RECORDER_TRACK_INFO_INITIAL_DELAY_MS  = 1007;
833    /** Provide the start time difference (delay) betweeen this track and
834     * the start of the movie.
835     * {@hide}
836     */
837    public static final int MEDIA_RECORDER_TRACK_INFO_START_OFFSET_MS   = 1008;
838    /** Provide the total number of data (in kilo-bytes) encoded.
839     * {@hide}
840     */
841    public static final int MEDIA_RECORDER_TRACK_INFO_DATA_KBYTES       = 1009;
842    /**
843     * {@hide}
844     */
845    public static final int MEDIA_RECORDER_TRACK_INFO_LIST_END          = 2000;
846
847
848    /**
849     * Interface definition for a callback to be invoked when an error
850     * occurs while recording.
851     */
852    public interface OnInfoListener
853    {
854        /**
855         * Called when an error occurs while recording.
856         *
857         * @param mr the MediaRecorder that encountered the error
858         * @param what    the type of error that has occurred:
859         * <ul>
860         * <li>{@link #MEDIA_RECORDER_INFO_UNKNOWN}
861         * <li>{@link #MEDIA_RECORDER_INFO_MAX_DURATION_REACHED}
862         * <li>{@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED}
863         * </ul>
864         * @param extra   an extra code, specific to the error type
865         */
866        void onInfo(MediaRecorder mr, int what, int extra);
867    }
868
869    /**
870     * Register a callback to be invoked when an informational event occurs while
871     * recording.
872     *
873     * @param listener the callback that will be run
874     */
875    public void setOnInfoListener(OnInfoListener listener)
876    {
877        mOnInfoListener = listener;
878    }
879
880    private class EventHandler extends Handler
881    {
882        private MediaRecorder mMediaRecorder;
883
884        public EventHandler(MediaRecorder mr, Looper looper) {
885            super(looper);
886            mMediaRecorder = mr;
887        }
888
889        /* Do not change these values without updating their counterparts
890         * in include/media/mediarecorder.h!
891         */
892        private static final int MEDIA_RECORDER_EVENT_LIST_START = 1;
893        private static final int MEDIA_RECORDER_EVENT_ERROR      = 1;
894        private static final int MEDIA_RECORDER_EVENT_INFO       = 2;
895        private static final int MEDIA_RECORDER_EVENT_LIST_END   = 99;
896
897        /* Events related to individual tracks */
898        private static final int MEDIA_RECORDER_TRACK_EVENT_LIST_START = 100;
899        private static final int MEDIA_RECORDER_TRACK_EVENT_ERROR      = 100;
900        private static final int MEDIA_RECORDER_TRACK_EVENT_INFO       = 101;
901        private static final int MEDIA_RECORDER_TRACK_EVENT_LIST_END   = 1000;
902
903
904        @Override
905        public void handleMessage(Message msg) {
906            if (mMediaRecorder.mNativeContext == 0) {
907                Log.w(TAG, "mediarecorder went away with unhandled events");
908                return;
909            }
910            switch(msg.what) {
911            case MEDIA_RECORDER_EVENT_ERROR:
912            case MEDIA_RECORDER_TRACK_EVENT_ERROR:
913                if (mOnErrorListener != null)
914                    mOnErrorListener.onError(mMediaRecorder, msg.arg1, msg.arg2);
915
916                return;
917
918            case MEDIA_RECORDER_EVENT_INFO:
919            case MEDIA_RECORDER_TRACK_EVENT_INFO:
920                if (mOnInfoListener != null)
921                    mOnInfoListener.onInfo(mMediaRecorder, msg.arg1, msg.arg2);
922
923                return;
924
925            default:
926                Log.e(TAG, "Unknown message type " + msg.what);
927                return;
928            }
929        }
930    }
931
932    /**
933     * Called from native code when an interesting event happens.  This method
934     * just uses the EventHandler system to post the event back to the main app thread.
935     * We use a weak reference to the original MediaRecorder object so that the native
936     * code is safe from the object disappearing from underneath it.  (This is
937     * the cookie passed to native_setup().)
938     */
939    private static void postEventFromNative(Object mediarecorder_ref,
940                                            int what, int arg1, int arg2, Object obj)
941    {
942        MediaRecorder mr = (MediaRecorder)((WeakReference)mediarecorder_ref).get();
943        if (mr == null) {
944            return;
945        }
946
947        if (mr.mEventHandler != null) {
948            Message m = mr.mEventHandler.obtainMessage(what, arg1, arg2, obj);
949            mr.mEventHandler.sendMessage(m);
950        }
951    }
952
953    /**
954     * Releases resources associated with this MediaRecorder object.
955     * It is good practice to call this method when you're done
956     * using the MediaRecorder. In particular, whenever an Activity
957     * of an application is paused (its onPause() method is called),
958     * or stopped (its onStop() method is called), this method should be
959     * invoked to release the MediaRecorder object, unless the application
960     * has a special need to keep the object around. In addition to
961     * unnecessary resources (such as memory and instances of codecs)
962     * being held, failure to call this method immediately if a
963     * MediaRecorder object is no longer needed may also lead to
964     * continuous battery consumption for mobile devices, and recording
965     * failure for other applications if no multiple instances of the
966     * same codec are supported on a device. Even if multiple instances
967     * of the same codec are supported, some performance degradation
968     * may be expected when unnecessary multiple instances are used
969     * at the same time.
970     */
971    public native void release();
972
973    private static native final void native_init();
974
975    private native final void native_setup(Object mediarecorder_this) throws IllegalStateException;
976
977    private native final void native_finalize();
978
979    private native void setParameter(String nameValuePair);
980
981    @Override
982    protected void finalize() { native_finalize(); }
983}
984