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