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