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