MediaRecorder.java revision 58a9cad4e88d3cf693b917b58677c392cdec24fc
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 Low Complexity (AAC-LC) audio codec */
255        public static final int AAC = 3;
256        /** High Efficiency AAC (HE-AAC) audio codec */
257        public static final int HE_AAC = 4;
258        /** Enhanced Low Delay AAC (AAC-ELD) audio codec */
259        public static final int AAC_ELD = 5;
260    }
261
262    /**
263     * Defines the video encoding. These constants are used with
264     * {@link MediaRecorder#setVideoEncoder(int)}.
265     */
266    public final class VideoEncoder {
267      /* Do not change these values without updating their counterparts
268       * in include/media/mediarecorder.h!
269       */
270        private VideoEncoder() {}
271        public static final int DEFAULT = 0;
272        public static final int H263 = 1;
273        public static final int H264 = 2;
274        public static final int MPEG_4_SP = 3;
275    }
276
277    /**
278     * Sets the audio source to be used for recording. If this method is not
279     * called, the output file will not contain an audio track. The source needs
280     * to be specified before setting recording-parameters or encoders. Call
281     * this only before setOutputFormat().
282     *
283     * @param audio_source the audio source to use
284     * @throws IllegalStateException if it is called after setOutputFormat()
285     * @see android.media.MediaRecorder.AudioSource
286     */
287    public native void setAudioSource(int audio_source)
288            throws IllegalStateException;
289
290    /**
291     * Gets the maximum value for audio sources.
292     * @see android.media.MediaRecorder.AudioSource
293     */
294    public static final int getAudioSourceMax() {
295        return AudioSource.VOICE_COMMUNICATION;
296    }
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("time-lapse-enable=1");
357
358        double timeBetweenFrameCapture = 1 / fps;
359        int timeBetweenFrameCaptureMs = (int) (1000 * timeBetweenFrameCapture);
360        setParameter("time-between-time-lapse-frame-capture=" + timeBetweenFrameCaptureMs);
361    }
362
363    /**
364     * Sets the orientation hint for output video playback.
365     * This method should be called before prepare(). This method will not
366     * trigger the source video frame to rotate during video recording, but to
367     * add a composition matrix containing the rotation angle in the output
368     * video if the output format is OutputFormat.THREE_GPP or
369     * OutputFormat.MPEG_4 so that a video player can choose the proper
370     * orientation for playback. Note that some video players may choose
371     * to ignore the compostion matrix in a video during playback.
372     *
373     * @param degrees the angle to be rotated clockwise in degrees.
374     * The supported angles are 0, 90, 180, and 270 degrees.
375     * @throws IllegalArgumentException if the angle is not supported.
376     *
377     */
378    public void setOrientationHint(int degrees) {
379        if (degrees != 0   &&
380            degrees != 90  &&
381            degrees != 180 &&
382            degrees != 270) {
383            throw new IllegalArgumentException("Unsupported angle: " + degrees);
384        }
385        setParameter("video-param-rotation-angle-degrees=" + degrees);
386    }
387
388    /**
389     * Set and store the geodata (latitude and longitude) in the output file.
390     * This method should be called before prepare(). The geodata is
391     * stored in udta box if the output format is OutputFormat.THREE_GPP
392     * or OutputFormat.MPEG_4, and is ignored for other output formats.
393     * The geodata is stored according to ISO-6709 standard.
394     *
395     * @param latitude latitude in degrees. Its value must be in the
396     * range [-90, 90].
397     * @param longitude longitude in degrees. Its value must be in the
398     * range [-180, 180].
399     *
400     * @throws IllegalArgumentException if the given latitude or
401     * longitude is out of range.
402     *
403     */
404    public void setLocation(float latitude, float longitude) {
405        int latitudex10000  = (int) (latitude * 10000 + 0.5);
406        int longitudex10000 = (int) (longitude * 10000 + 0.5);
407
408        if (latitudex10000 > 900000 || latitudex10000 < -900000) {
409            String msg = "Latitude: " + latitude + " out of range.";
410            throw new IllegalArgumentException(msg);
411        }
412        if (longitudex10000 > 1800000 || longitudex10000 < -1800000) {
413            String msg = "Longitude: " + longitude + " out of range";
414            throw new IllegalArgumentException(msg);
415        }
416
417        setParameter("param-geotag-latitude=" + latitudex10000);
418        setParameter("param-geotag-longitude=" + longitudex10000);
419    }
420
421    /**
422     * Sets the format of the output file produced during recording. Call this
423     * after setAudioSource()/setVideoSource() but before prepare().
424     *
425     * <p>It is recommended to always use 3GP format when using the H.263
426     * video encoder and AMR audio encoder. Using an MPEG-4 container format
427     * may confuse some desktop players.</p>
428     *
429     * @param output_format the output format to use. The output format
430     * needs to be specified before setting recording-parameters or encoders.
431     * @throws IllegalStateException if it is called after prepare() or before
432     * setAudioSource()/setVideoSource().
433     * @see android.media.MediaRecorder.OutputFormat
434     */
435    public native void setOutputFormat(int output_format)
436            throws IllegalStateException;
437
438    /**
439     * Sets the width and height of the video to be captured.  Must be called
440     * after setVideoSource(). Call this after setOutFormat() but before
441     * prepare().
442     *
443     * @param width the width of the video to be captured
444     * @param height the height of the video to be captured
445     * @throws IllegalStateException if it is called after
446     * prepare() or before setOutputFormat()
447     */
448    public native void setVideoSize(int width, int height)
449            throws IllegalStateException;
450
451    /**
452     * Sets the frame rate of the video to be captured.  Must be called
453     * after setVideoSource(). Call this after setOutFormat() but before
454     * prepare().
455     *
456     * @param rate the number of frames per second of video to capture
457     * @throws IllegalStateException if it is called after
458     * prepare() or before setOutputFormat().
459     *
460     * NOTE: On some devices that have auto-frame rate, this sets the
461     * maximum frame rate, not a constant frame rate. Actual frame rate
462     * will vary according to lighting conditions.
463     */
464    public native void setVideoFrameRate(int rate) throws IllegalStateException;
465
466    /**
467     * Sets the maximum duration (in ms) of the recording session.
468     * Call this after setOutFormat() but before prepare().
469     * After recording reaches the specified duration, a notification
470     * will be sent to the {@link android.media.MediaRecorder.OnInfoListener}
471     * with a "what" code of {@link #MEDIA_RECORDER_INFO_MAX_DURATION_REACHED}
472     * and recording will be stopped. Stopping happens asynchronously, there
473     * is no guarantee that the recorder will have stopped by the time the
474     * listener is notified.
475     *
476     * @param max_duration_ms the maximum duration in ms (if zero or negative, disables the duration limit)
477     *
478     */
479    public native void setMaxDuration(int max_duration_ms) throws IllegalArgumentException;
480
481    /**
482     * Sets the maximum filesize (in bytes) of the recording session.
483     * Call this after setOutFormat() but before prepare().
484     * After recording reaches the specified filesize, a notification
485     * will be sent to the {@link android.media.MediaRecorder.OnInfoListener}
486     * with a "what" code of {@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED}
487     * and recording will be stopped. Stopping happens asynchronously, there
488     * is no guarantee that the recorder will have stopped by the time the
489     * listener is notified.
490     *
491     * @param max_filesize_bytes the maximum filesize in bytes (if zero or negative, disables the limit)
492     *
493     */
494    public native void setMaxFileSize(long max_filesize_bytes) throws IllegalArgumentException;
495
496    /**
497     * Sets the audio encoder to be used for recording. If this method is not
498     * called, the output file will not contain an audio track. Call this after
499     * setOutputFormat() but before prepare().
500     *
501     * @param audio_encoder the audio encoder to use.
502     * @throws IllegalStateException if it is called before
503     * setOutputFormat() or after prepare().
504     * @see android.media.MediaRecorder.AudioEncoder
505     */
506    public native void setAudioEncoder(int audio_encoder)
507            throws IllegalStateException;
508
509    /**
510     * Sets the video encoder to be used for recording. If this method is not
511     * called, the output file will not contain an video track. Call this after
512     * setOutputFormat() and before prepare().
513     *
514     * @param video_encoder the video encoder to use.
515     * @throws IllegalStateException if it is called before
516     * setOutputFormat() or after prepare()
517     * @see android.media.MediaRecorder.VideoEncoder
518     */
519    public native void setVideoEncoder(int video_encoder)
520            throws IllegalStateException;
521
522    /**
523     * Sets the audio sampling rate for recording. Call this method before prepare().
524     * Prepare() may perform additional checks on the parameter to make sure whether
525     * the specified audio sampling rate is applicable. The sampling rate really depends
526     * on the format for the audio recording, as well as the capabilities of the platform.
527     * For instance, the sampling rate supported by AAC audio coding standard ranges
528     * from 8 to 96 kHz, the sampling rate supported by AMRNB is 8kHz, and the sampling
529     * rate supported by AMRWB is 16kHz. Please consult with the related audio coding
530     * standard for the supported audio sampling rate.
531     *
532     * @param samplingRate the sampling rate for audio in samples per second.
533     */
534    public void setAudioSamplingRate(int samplingRate) {
535        if (samplingRate <= 0) {
536            throw new IllegalArgumentException("Audio sampling rate is not positive");
537        }
538        setParameter("audio-param-sampling-rate=" + samplingRate);
539    }
540
541    /**
542     * Sets the number of audio channels for recording. Call this method before prepare().
543     * Prepare() may perform additional checks on the parameter to make sure whether the
544     * specified number of audio channels are applicable.
545     *
546     * @param numChannels the number of audio channels. Usually it is either 1 (mono) or 2
547     * (stereo).
548     */
549    public void setAudioChannels(int numChannels) {
550        if (numChannels <= 0) {
551            throw new IllegalArgumentException("Number of channels is not positive");
552        }
553        setParameter("audio-param-number-of-channels=" + numChannels);
554    }
555
556    /**
557     * Sets the audio encoding bit rate for recording. Call this method before prepare().
558     * Prepare() may perform additional checks on the parameter to make sure whether the
559     * specified bit rate is applicable, and sometimes the passed bitRate will be clipped
560     * internally to ensure the audio recording can proceed smoothly based on the
561     * capabilities of the platform.
562     *
563     * @param bitRate the audio encoding bit rate in bits per second.
564     */
565    public void setAudioEncodingBitRate(int bitRate) {
566        if (bitRate <= 0) {
567            throw new IllegalArgumentException("Audio encoding bit rate is not positive");
568        }
569        setParameter("audio-param-encoding-bitrate=" + bitRate);
570    }
571
572    /**
573     * Sets the video encoding bit rate for recording. Call this method before prepare().
574     * Prepare() may perform additional checks on the parameter to make sure whether the
575     * specified bit rate is applicable, and sometimes the passed bitRate will be
576     * clipped internally to ensure the video recording can proceed smoothly based on
577     * the capabilities of the platform.
578     *
579     * @param bitRate the video encoding bit rate in bits per second.
580     */
581    public void setVideoEncodingBitRate(int bitRate) {
582        if (bitRate <= 0) {
583            throw new IllegalArgumentException("Video encoding bit rate is not positive");
584        }
585        setParameter("video-param-encoding-bitrate=" + bitRate);
586    }
587
588    /**
589     * Currently not implemented. It does nothing.
590     * @deprecated Time lapse mode video recording using camera still image capture
591     * is not desirable, and will not be supported.
592     * @hide
593     */
594    public void setAuxiliaryOutputFile(FileDescriptor fd)
595    {
596        Log.w(TAG, "setAuxiliaryOutputFile(FileDescriptor) is no longer supported.");
597    }
598
599    /**
600     * Currently not implemented. It does nothing.
601     * @deprecated Time lapse mode video recording using camera still image capture
602     * is not desirable, and will not be supported.
603     * @hide
604     */
605    public void setAuxiliaryOutputFile(String path)
606    {
607        Log.w(TAG, "setAuxiliaryOutputFile(String) is no longer supported.");
608    }
609
610    /**
611     * Pass in the file descriptor of the file to be written. Call this after
612     * setOutputFormat() but before prepare().
613     *
614     * @param fd an open file descriptor to be written into.
615     * @throws IllegalStateException if it is called before
616     * setOutputFormat() or after prepare()
617     */
618    public void setOutputFile(FileDescriptor fd) throws IllegalStateException
619    {
620        mPath = null;
621        mFd = fd;
622    }
623
624    /**
625     * Sets the path of the output file to be produced. Call this after
626     * setOutputFormat() but before prepare().
627     *
628     * @param path The pathname to use.
629     * @throws IllegalStateException if it is called before
630     * setOutputFormat() or after prepare()
631     */
632    public void setOutputFile(String path) throws IllegalStateException
633    {
634        mFd = null;
635        mPath = path;
636    }
637
638    // native implementation
639    private native void _setOutputFile(FileDescriptor fd, long offset, long length)
640        throws IllegalStateException, IOException;
641    private native void _prepare() throws IllegalStateException, IOException;
642
643    /**
644     * Prepares the recorder to begin capturing and encoding data. This method
645     * must be called after setting up the desired audio and video sources,
646     * encoders, file format, etc., but before start().
647     *
648     * @throws IllegalStateException if it is called after
649     * start() or before setOutputFormat().
650     * @throws IOException if prepare fails otherwise.
651     */
652    public void prepare() throws IllegalStateException, IOException
653    {
654        if (mPath != null) {
655            FileOutputStream fos = new FileOutputStream(mPath);
656            try {
657                _setOutputFile(fos.getFD(), 0, 0);
658            } finally {
659                fos.close();
660            }
661        } else if (mFd != null) {
662            _setOutputFile(mFd, 0, 0);
663        } else {
664            throw new IOException("No valid output file");
665        }
666
667        _prepare();
668    }
669
670    /**
671     * Begins capturing and encoding data to the file specified with
672     * setOutputFile(). Call this after prepare().
673     *
674     * <p>Since API level 13, if applications set a camera via
675     * {@link #setCamera(Camera)}, the apps can use the camera after this method
676     * call. The apps do not need to lock the camera again. However, if this
677     * method fails, the apps should still lock the camera back. The apps should
678     * not start another recording session during recording.
679     *
680     * @throws IllegalStateException if it is called before
681     * prepare().
682     */
683    public native void start() throws IllegalStateException;
684
685    /**
686     * Stops recording. Call this after start(). Once recording is stopped,
687     * you will have to configure it again as if it has just been constructed.
688     * Note that a RuntimeException is intentionally thrown to the
689     * application, if no valid audio/video data has been received when stop()
690     * is called. This happens if stop() is called immediately after
691     * start(). The failure lets the application take action accordingly to
692     * clean up the output file (delete the output file, for instance), since
693     * the output file is not properly constructed when this happens.
694     *
695     * @throws IllegalStateException if it is called before start()
696     */
697    public native void stop() throws IllegalStateException;
698
699    /**
700     * Restarts the MediaRecorder to its idle state. After calling
701     * this method, you will have to configure it again as if it had just been
702     * constructed.
703     */
704    public void reset() {
705        native_reset();
706
707        // make sure none of the listeners get called anymore
708        mEventHandler.removeCallbacksAndMessages(null);
709    }
710
711    private native void native_reset();
712
713    /**
714     * Returns the maximum absolute amplitude that was sampled since the last
715     * call to this method. Call this only after the setAudioSource().
716     *
717     * @return the maximum absolute amplitude measured since the last call, or
718     * 0 when called for the first time
719     * @throws IllegalStateException if it is called before
720     * the audio source has been set.
721     */
722    public native int getMaxAmplitude() throws IllegalStateException;
723
724    /* Do not change this value without updating its counterpart
725     * in include/media/mediarecorder.h or mediaplayer.h!
726     */
727    /** Unspecified media recorder error.
728     * @see android.media.MediaRecorder.OnErrorListener
729     */
730    public static final int MEDIA_RECORDER_ERROR_UNKNOWN = 1;
731    /** Media server died. In this case, the application must release the
732     * MediaRecorder object and instantiate a new one.
733     * @see android.media.MediaRecorder.OnErrorListener
734     */
735    public static final int MEDIA_ERROR_SERVER_DIED = 100;
736
737    /**
738     * Interface definition for a callback to be invoked when an error
739     * occurs while recording.
740     */
741    public interface OnErrorListener
742    {
743        /**
744         * Called when an error occurs while recording.
745         *
746         * @param mr the MediaRecorder that encountered the error
747         * @param what    the type of error that has occurred:
748         * <ul>
749         * <li>{@link #MEDIA_RECORDER_ERROR_UNKNOWN}
750         * <li>{@link #MEDIA_ERROR_SERVER_DIED}
751         * </ul>
752         * @param extra   an extra code, specific to the error type
753         */
754        void onError(MediaRecorder mr, int what, int extra);
755    }
756
757    /**
758     * Register a callback to be invoked when an error occurs while
759     * recording.
760     *
761     * @param l the callback that will be run
762     */
763    public void setOnErrorListener(OnErrorListener l)
764    {
765        mOnErrorListener = l;
766    }
767
768    /* Do not change these values without updating their counterparts
769     * in include/media/mediarecorder.h!
770     */
771    /** Unspecified media recorder error.
772     * @see android.media.MediaRecorder.OnInfoListener
773     */
774    public static final int MEDIA_RECORDER_INFO_UNKNOWN              = 1;
775    /** A maximum duration had been setup and has now been reached.
776     * @see android.media.MediaRecorder.OnInfoListener
777     */
778    public static final int MEDIA_RECORDER_INFO_MAX_DURATION_REACHED = 800;
779    /** A maximum filesize had been setup and has now been reached.
780     * @see android.media.MediaRecorder.OnInfoListener
781     */
782    public static final int MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED = 801;
783
784    /** informational events for individual tracks, for testing purpose.
785     * The track informational event usually contains two parts in the ext1
786     * arg of the onInfo() callback: bit 31-28 contains the track id; and
787     * the rest of the 28 bits contains the informational event defined here.
788     * For example, ext1 = (1 << 28 | MEDIA_RECORDER_TRACK_INFO_TYPE) if the
789     * track id is 1 for informational event MEDIA_RECORDER_TRACK_INFO_TYPE;
790     * while ext1 = (0 << 28 | MEDIA_RECORDER_TRACK_INFO_TYPE) if the track
791     * id is 0 for informational event MEDIA_RECORDER_TRACK_INFO_TYPE. The
792     * application should extract the track id and the type of informational
793     * event from ext1, accordingly.
794     *
795     * FIXME:
796     * Please update the comment for onInfo also when these
797     * events are unhidden so that application knows how to extract the track
798     * id and the informational event type from onInfo callback.
799     *
800     * {@hide}
801     */
802    public static final int MEDIA_RECORDER_TRACK_INFO_LIST_START        = 1000;
803    /** Signal the completion of the track for the recording session.
804     * {@hide}
805     */
806    public static final int MEDIA_RECORDER_TRACK_INFO_COMPLETION_STATUS = 1000;
807    /** Indicate the recording progress in time (ms) during recording.
808     * {@hide}
809     */
810    public static final int MEDIA_RECORDER_TRACK_INFO_PROGRESS_IN_TIME  = 1001;
811    /** Indicate the track type: 0 for Audio and 1 for Video.
812     * {@hide}
813     */
814    public static final int MEDIA_RECORDER_TRACK_INFO_TYPE              = 1002;
815    /** Provide the track duration information.
816     * {@hide}
817     */
818    public static final int MEDIA_RECORDER_TRACK_INFO_DURATION_MS       = 1003;
819    /** Provide the max chunk duration in time (ms) for the given track.
820     * {@hide}
821     */
822    public static final int MEDIA_RECORDER_TRACK_INFO_MAX_CHUNK_DUR_MS  = 1004;
823    /** Provide the total number of recordd frames.
824     * {@hide}
825     */
826    public static final int MEDIA_RECORDER_TRACK_INFO_ENCODED_FRAMES    = 1005;
827    /** Provide the max spacing between neighboring chunks for the given track.
828     * {@hide}
829     */
830    public static final int MEDIA_RECORDER_TRACK_INTER_CHUNK_TIME_MS    = 1006;
831    /** Provide the elapsed time measuring from the start of the recording
832     * till the first output frame of the given track is received, excluding
833     * any intentional start time offset of a recording session for the
834     * purpose of eliminating the recording sound in the recorded file.
835     * {@hide}
836     */
837    public static final int MEDIA_RECORDER_TRACK_INFO_INITIAL_DELAY_MS  = 1007;
838    /** Provide the start time difference (delay) betweeen this track and
839     * the start of the movie.
840     * {@hide}
841     */
842    public static final int MEDIA_RECORDER_TRACK_INFO_START_OFFSET_MS   = 1008;
843    /** Provide the total number of data (in kilo-bytes) encoded.
844     * {@hide}
845     */
846    public static final int MEDIA_RECORDER_TRACK_INFO_DATA_KBYTES       = 1009;
847    /**
848     * {@hide}
849     */
850    public static final int MEDIA_RECORDER_TRACK_INFO_LIST_END          = 2000;
851
852
853    /**
854     * Interface definition for a callback to be invoked when an error
855     * occurs while recording.
856     */
857    public interface OnInfoListener
858    {
859        /**
860         * Called when an error occurs while recording.
861         *
862         * @param mr the MediaRecorder that encountered the error
863         * @param what    the type of error that has occurred:
864         * <ul>
865         * <li>{@link #MEDIA_RECORDER_INFO_UNKNOWN}
866         * <li>{@link #MEDIA_RECORDER_INFO_MAX_DURATION_REACHED}
867         * <li>{@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED}
868         * </ul>
869         * @param extra   an extra code, specific to the error type
870         */
871        void onInfo(MediaRecorder mr, int what, int extra);
872    }
873
874    /**
875     * Register a callback to be invoked when an informational event occurs while
876     * recording.
877     *
878     * @param listener the callback that will be run
879     */
880    public void setOnInfoListener(OnInfoListener listener)
881    {
882        mOnInfoListener = listener;
883    }
884
885    private class EventHandler extends Handler
886    {
887        private MediaRecorder mMediaRecorder;
888
889        public EventHandler(MediaRecorder mr, Looper looper) {
890            super(looper);
891            mMediaRecorder = mr;
892        }
893
894        /* Do not change these values without updating their counterparts
895         * in include/media/mediarecorder.h!
896         */
897        private static final int MEDIA_RECORDER_EVENT_LIST_START = 1;
898        private static final int MEDIA_RECORDER_EVENT_ERROR      = 1;
899        private static final int MEDIA_RECORDER_EVENT_INFO       = 2;
900        private static final int MEDIA_RECORDER_EVENT_LIST_END   = 99;
901
902        /* Events related to individual tracks */
903        private static final int MEDIA_RECORDER_TRACK_EVENT_LIST_START = 100;
904        private static final int MEDIA_RECORDER_TRACK_EVENT_ERROR      = 100;
905        private static final int MEDIA_RECORDER_TRACK_EVENT_INFO       = 101;
906        private static final int MEDIA_RECORDER_TRACK_EVENT_LIST_END   = 1000;
907
908
909        @Override
910        public void handleMessage(Message msg) {
911            if (mMediaRecorder.mNativeContext == 0) {
912                Log.w(TAG, "mediarecorder went away with unhandled events");
913                return;
914            }
915            switch(msg.what) {
916            case MEDIA_RECORDER_EVENT_ERROR:
917            case MEDIA_RECORDER_TRACK_EVENT_ERROR:
918                if (mOnErrorListener != null)
919                    mOnErrorListener.onError(mMediaRecorder, msg.arg1, msg.arg2);
920
921                return;
922
923            case MEDIA_RECORDER_EVENT_INFO:
924            case MEDIA_RECORDER_TRACK_EVENT_INFO:
925                if (mOnInfoListener != null)
926                    mOnInfoListener.onInfo(mMediaRecorder, msg.arg1, msg.arg2);
927
928                return;
929
930            default:
931                Log.e(TAG, "Unknown message type " + msg.what);
932                return;
933            }
934        }
935    }
936
937    /**
938     * Called from native code when an interesting event happens.  This method
939     * just uses the EventHandler system to post the event back to the main app thread.
940     * We use a weak reference to the original MediaRecorder object so that the native
941     * code is safe from the object disappearing from underneath it.  (This is
942     * the cookie passed to native_setup().)
943     */
944    private static void postEventFromNative(Object mediarecorder_ref,
945                                            int what, int arg1, int arg2, Object obj)
946    {
947        MediaRecorder mr = (MediaRecorder)((WeakReference)mediarecorder_ref).get();
948        if (mr == null) {
949            return;
950        }
951
952        if (mr.mEventHandler != null) {
953            Message m = mr.mEventHandler.obtainMessage(what, arg1, arg2, obj);
954            mr.mEventHandler.sendMessage(m);
955        }
956    }
957
958    /**
959     * Releases resources associated with this MediaRecorder object.
960     * It is good practice to call this method when you're done
961     * using the MediaRecorder. In particular, whenever an Activity
962     * of an application is paused (its onPause() method is called),
963     * or stopped (its onStop() method is called), this method should be
964     * invoked to release the MediaRecorder object, unless the application
965     * has a special need to keep the object around. In addition to
966     * unnecessary resources (such as memory and instances of codecs)
967     * being held, failure to call this method immediately if a
968     * MediaRecorder object is no longer needed may also lead to
969     * continuous battery consumption for mobile devices, and recording
970     * failure for other applications if no multiple instances of the
971     * same codec are supported on a device. Even if multiple instances
972     * of the same codec are supported, some performance degradation
973     * may be expected when unnecessary multiple instances are used
974     * at the same time.
975     */
976    public native void release();
977
978    private static native final void native_init();
979
980    private native final void native_setup(Object mediarecorder_this) throws IllegalStateException;
981
982    private native final void native_finalize();
983
984    private native void setParameter(String nameValuePair);
985
986    @Override
987    protected void finalize() { native_finalize(); }
988}
989