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