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