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