MediaRecorder.java revision 64dfb604e70b70b7c346768114e05ddfadc09add
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.app.ActivityThread;
20import android.hardware.Camera;
21import android.os.Handler;
22import android.os.Looper;
23import android.os.Message;
24import android.util.Log;
25import android.view.Surface;
26
27import java.io.FileDescriptor;
28import java.io.FileOutputStream;
29import java.io.IOException;
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>Applications may want to register for informational and error
55 * events in order to be informed of some internal update and possible
56 * runtime errors during recording. Registration for such events is
57 * done by setting the appropriate listeners (via calls
58 * (to {@link #setOnInfoListener(OnInfoListener)}setOnInfoListener and/or
59 * {@link #setOnErrorListener(OnErrorListener)}setOnErrorListener).
60 * In order to receive the respective callback associated with these listeners,
61 * applications are required to create MediaRecorder objects on threads with a
62 * Looper running (the main UI thread by default already has a Looper running).
63 *
64 * <p><strong>Note:</strong> Currently, MediaRecorder does not work on the emulator.
65 *
66 * <div class="special reference">
67 * <h3>Developer Guides</h3>
68 * <p>For more information about how to use MediaRecorder for recording video, read the
69 * <a href="{@docRoot}guide/topics/media/camera.html#capture-video">Camera</a> developer guide.
70 * For more information about how to use MediaRecorder for recording sound, read the
71 * <a href="{@docRoot}guide/topics/media/audio-capture.html">Audio Capture</a> developer guide.</p>
72 * </div>
73 */
74public class MediaRecorder
75{
76    static {
77        System.loadLibrary("media_jni");
78        native_init();
79    }
80    private final static String TAG = "MediaRecorder";
81
82    // The two fields below are accessed by native methods
83    @SuppressWarnings("unused")
84    private int mNativeContext;
85
86    @SuppressWarnings("unused")
87    private Surface mSurface;
88
89    private String mPath;
90    private FileDescriptor mFd;
91    private EventHandler mEventHandler;
92    private OnErrorListener mOnErrorListener;
93    private OnInfoListener mOnInfoListener;
94
95    /**
96     * Default constructor.
97     */
98    public MediaRecorder() {
99
100        Looper looper;
101        if ((looper = Looper.myLooper()) != null) {
102            mEventHandler = new EventHandler(this, looper);
103        } else if ((looper = Looper.getMainLooper()) != null) {
104            mEventHandler = new EventHandler(this, looper);
105        } else {
106            mEventHandler = null;
107        }
108
109        String packageName = ActivityThread.currentPackageName();
110        /* Native setup requires a weak reference to our object.
111         * It's easier to create it here than in C++.
112         */
113        native_setup(new WeakReference<MediaRecorder>(this), packageName);
114    }
115
116    /**
117     * Sets a Camera to use for recording. Use this function to switch
118     * quickly between preview and capture mode without a teardown of
119     * the camera object. {@link android.hardware.Camera#unlock()} should be
120     * called before this. Must call before prepare().
121     *
122     * @param c the Camera to use for recording
123     */
124    public native void setCamera(Camera c);
125
126    /**
127     * Sets a Surface to show a preview of recorded media (video). Calls this
128     * before prepare() to make sure that the desirable preview display is
129     * set. If {@link #setCamera(Camera)} is used and the surface has been
130     * already set to the camera, application do not need to call this. If
131     * this is called with non-null surface, the preview surface of the camera
132     * will be replaced by the new surface. If this method is called with null
133     * surface or not called at all, media recorder will not change the preview
134     * surface of the camera.
135     *
136     * @param sv the Surface to use for the preview
137     * @see android.hardware.Camera#setPreviewDisplay(android.view.SurfaceHolder)
138     */
139    public void setPreviewDisplay(Surface sv) {
140        mSurface = sv;
141    }
142
143    /**
144     * Defines the audio source. These constants are used with
145     * {@link MediaRecorder#setAudioSource(int)}.
146     */
147    public final class AudioSource {
148      /* Do not change these values without updating their counterparts
149       * in system/core/include/system/audio.h!
150       */
151        private AudioSource() {}
152
153        /** Default audio source **/
154        public static final int DEFAULT = 0;
155
156        /** Microphone audio source */
157        public static final int MIC = 1;
158
159        /** Voice call uplink (Tx) audio source */
160        public static final int VOICE_UPLINK = 2;
161
162        /** Voice call downlink (Rx) audio source */
163        public static final int VOICE_DOWNLINK = 3;
164
165        /** Voice call uplink + downlink audio source */
166        public static final int VOICE_CALL = 4;
167
168        /** Microphone audio source with same orientation as camera if available, the main
169         *  device microphone otherwise */
170        public static final int CAMCORDER = 5;
171
172        /** Microphone audio source tuned for voice recognition if available, behaves like
173         *  {@link #DEFAULT} otherwise. */
174        public static final int VOICE_RECOGNITION = 6;
175
176        /** Microphone audio source tuned for voice communications such as VoIP. It
177         *  will for instance take advantage of echo cancellation or automatic gain control
178         *  if available. It otherwise behaves like {@link #DEFAULT} if no voice processing
179         *  is applied.
180         */
181        public static final int VOICE_COMMUNICATION = 7;
182
183        /**
184         * Audio source for a submix of audio streams to be presented remotely.
185         * <p>
186         * An application can use this audio source to capture a mix of audio streams
187         * that should be transmitted to a remote receiver such as a Wifi display.
188         * While recording is active, these audio streams are redirected to the remote
189         * submix instead of being played on the device speaker or headset.
190         * </p><p>
191         * Certain streams are excluded from the remote submix, including
192         * {@link AudioManager#STREAM_RING}, {@link AudioManager#STREAM_ALARM},
193         * and {@link AudioManager#STREAM_NOTIFICATION}.  These streams will continue
194         * to be presented locally as usual.
195         * </p><p>
196         * Capturing the remote submix audio requires the
197         * {@link android.Manifest.permission#CAPTURE_AUDIO_OUTPUT} permission.
198         * This permission is reserved for use by system components and is not available to
199         * third-party applications.
200         * </p>
201         */
202        public static final int REMOTE_SUBMIX = 8;
203    }
204
205    /**
206     * Defines the video source. These constants are used with
207     * {@link MediaRecorder#setVideoSource(int)}.
208     */
209    public final class VideoSource {
210      /* Do not change these values without updating their counterparts
211       * in include/media/mediarecorder.h!
212       */
213        private VideoSource() {}
214        public static final int DEFAULT = 0;
215        /** Camera video source */
216        public static final int CAMERA = 1;
217        /** @hide */
218        public static final int GRALLOC_BUFFER = 2;
219    }
220
221    /**
222     * Defines the output format. These constants are used with
223     * {@link MediaRecorder#setOutputFormat(int)}.
224     */
225    public final class OutputFormat {
226      /* Do not change these values without updating their counterparts
227       * in include/media/mediarecorder.h!
228       */
229        private OutputFormat() {}
230        public static final int DEFAULT = 0;
231        /** 3GPP media file format*/
232        public static final int THREE_GPP = 1;
233        /** MPEG4 media file format*/
234        public static final int MPEG_4 = 2;
235
236        /** The following formats are audio only .aac or .amr formats */
237
238        /**
239         * AMR NB file format
240         * @deprecated  Deprecated in favor of MediaRecorder.OutputFormat.AMR_NB
241         */
242        public static final int RAW_AMR = 3;
243
244        /** AMR NB file format */
245        public static final int AMR_NB = 3;
246
247        /** AMR WB file format */
248        public static final int AMR_WB = 4;
249
250        /** @hide AAC ADIF file format */
251        public static final int AAC_ADIF = 5;
252
253        /** AAC ADTS file format */
254        public static final int AAC_ADTS = 6;
255
256        /** @hide Stream over a socket, limited to a single stream */
257        public static final int OUTPUT_FORMAT_RTP_AVP = 7;
258
259        /** @hide H.264/AAC data encapsulated in MPEG2/TS */
260        public static final int OUTPUT_FORMAT_MPEG2TS = 8;
261    };
262
263    /**
264     * Defines the audio encoding. These constants are used with
265     * {@link MediaRecorder#setAudioEncoder(int)}.
266     */
267    public final class AudioEncoder {
268      /* Do not change these values without updating their counterparts
269       * in include/media/mediarecorder.h!
270       */
271        private AudioEncoder() {}
272        public static final int DEFAULT = 0;
273        /** AMR (Narrowband) audio codec */
274        public static final int AMR_NB = 1;
275        /** AMR (Wideband) audio codec */
276        public static final int AMR_WB = 2;
277        /** AAC Low Complexity (AAC-LC) audio codec */
278        public static final int AAC = 3;
279        /** High Efficiency AAC (HE-AAC) audio codec */
280        public static final int HE_AAC = 4;
281        /** Enhanced Low Delay AAC (AAC-ELD) audio codec */
282        public static final int AAC_ELD = 5;
283    }
284
285    /**
286     * Defines the video encoding. These constants are used with
287     * {@link MediaRecorder#setVideoEncoder(int)}.
288     */
289    public final class VideoEncoder {
290      /* Do not change these values without updating their counterparts
291       * in include/media/mediarecorder.h!
292       */
293        private VideoEncoder() {}
294        public static final int DEFAULT = 0;
295        public static final int H263 = 1;
296        public static final int H264 = 2;
297        public static final int MPEG_4_SP = 3;
298    }
299
300    /**
301     * Sets the audio source to be used for recording. If this method is not
302     * called, the output file will not contain an audio track. The source needs
303     * to be specified before setting recording-parameters or encoders. Call
304     * this only before setOutputFormat().
305     *
306     * @param audio_source the audio source to use
307     * @throws IllegalStateException if it is called after setOutputFormat()
308     * @see android.media.MediaRecorder.AudioSource
309     */
310    public native void setAudioSource(int audio_source)
311            throws IllegalStateException;
312
313    /**
314     * Gets the maximum value for audio sources.
315     * @see android.media.MediaRecorder.AudioSource
316     */
317    public static final int getAudioSourceMax() {
318        return AudioSource.REMOTE_SUBMIX;
319    }
320
321    /**
322     * Sets the video source to be used for recording. If this method is not
323     * called, the output file will not contain an video track. The source needs
324     * to be specified before setting recording-parameters or encoders. Call
325     * this only before setOutputFormat().
326     *
327     * @param video_source the video source to use
328     * @throws IllegalStateException if it is called after setOutputFormat()
329     * @see android.media.MediaRecorder.VideoSource
330     */
331    public native void setVideoSource(int video_source)
332            throws IllegalStateException;
333
334    /**
335     * Uses the settings from a CamcorderProfile object for recording. This method should
336     * be called after the video AND audio sources are set, and before setOutputFile().
337     * If a time lapse CamcorderProfile is used, audio related source or recording
338     * parameters are ignored.
339     *
340     * @param profile the CamcorderProfile to use
341     * @see android.media.CamcorderProfile
342     */
343    public void setProfile(CamcorderProfile profile) {
344        setOutputFormat(profile.fileFormat);
345        setVideoFrameRate(profile.videoFrameRate);
346        setVideoSize(profile.videoFrameWidth, profile.videoFrameHeight);
347        setVideoEncodingBitRate(profile.videoBitRate);
348        setVideoEncoder(profile.videoCodec);
349        if (profile.quality >= CamcorderProfile.QUALITY_TIME_LAPSE_LOW &&
350             profile.quality <= CamcorderProfile.QUALITY_TIME_LAPSE_QVGA) {
351            // Nothing needs to be done. Call to setCaptureRate() enables
352            // time lapse video recording.
353        } else {
354            setAudioEncodingBitRate(profile.audioBitRate);
355            setAudioChannels(profile.audioChannels);
356            setAudioSamplingRate(profile.audioSampleRate);
357            setAudioEncoder(profile.audioCodec);
358        }
359    }
360
361    /**
362     * Set video frame capture rate. This can be used to set a different video frame capture
363     * rate than the recorded video's playback rate. This method also sets the recording mode
364     * to time lapse. In time lapse video recording, only video is recorded. Audio related
365     * parameters are ignored when a time lapse recording session starts, if an application
366     * sets them.
367     *
368     * @param fps Rate at which frames should be captured in frames per second.
369     * The fps can go as low as desired. However the fastest fps will be limited by the hardware.
370     * For resolutions that can be captured by the video camera, the fastest fps can be computed using
371     * {@link android.hardware.Camera.Parameters#getPreviewFpsRange(int[])}. For higher
372     * resolutions the fastest fps may be more restrictive.
373     * Note that the recorder cannot guarantee that frames will be captured at the
374     * given rate due to camera/encoder limitations. However it tries to be as close as
375     * possible.
376     */
377    public void setCaptureRate(double fps) {
378        // Make sure that time lapse is enabled when this method is called.
379        setParameter("time-lapse-enable=1");
380
381        double timeBetweenFrameCapture = 1 / fps;
382        int timeBetweenFrameCaptureMs = (int) (1000 * timeBetweenFrameCapture);
383        setParameter("time-between-time-lapse-frame-capture=" + timeBetweenFrameCaptureMs);
384    }
385
386    /**
387     * Sets the orientation hint for output video playback.
388     * This method should be called before prepare(). This method will not
389     * trigger the source video frame to rotate during video recording, but to
390     * add a composition matrix containing the rotation angle in the output
391     * video if the output format is OutputFormat.THREE_GPP or
392     * OutputFormat.MPEG_4 so that a video player can choose the proper
393     * orientation for playback. Note that some video players may choose
394     * to ignore the compostion matrix in a video during playback.
395     *
396     * @param degrees the angle to be rotated clockwise in degrees.
397     * The supported angles are 0, 90, 180, and 270 degrees.
398     * @throws IllegalArgumentException if the angle is not supported.
399     *
400     */
401    public void setOrientationHint(int degrees) {
402        if (degrees != 0   &&
403            degrees != 90  &&
404            degrees != 180 &&
405            degrees != 270) {
406            throw new IllegalArgumentException("Unsupported angle: " + degrees);
407        }
408        setParameter("video-param-rotation-angle-degrees=" + degrees);
409    }
410
411    /**
412     * Set and store the geodata (latitude and longitude) in the output file.
413     * This method should be called before prepare(). The geodata is
414     * stored in udta box if the output format is OutputFormat.THREE_GPP
415     * or OutputFormat.MPEG_4, and is ignored for other output formats.
416     * The geodata is stored according to ISO-6709 standard.
417     *
418     * @param latitude latitude in degrees. Its value must be in the
419     * range [-90, 90].
420     * @param longitude longitude in degrees. Its value must be in the
421     * range [-180, 180].
422     *
423     * @throws IllegalArgumentException if the given latitude or
424     * longitude is out of range.
425     *
426     */
427    public void setLocation(float latitude, float longitude) {
428        int latitudex10000  = (int) (latitude * 10000 + 0.5);
429        int longitudex10000 = (int) (longitude * 10000 + 0.5);
430
431        if (latitudex10000 > 900000 || latitudex10000 < -900000) {
432            String msg = "Latitude: " + latitude + " out of range.";
433            throw new IllegalArgumentException(msg);
434        }
435        if (longitudex10000 > 1800000 || longitudex10000 < -1800000) {
436            String msg = "Longitude: " + longitude + " out of range";
437            throw new IllegalArgumentException(msg);
438        }
439
440        setParameter("param-geotag-latitude=" + latitudex10000);
441        setParameter("param-geotag-longitude=" + longitudex10000);
442    }
443
444    /**
445     * Sets the format of the output file produced during recording. Call this
446     * after setAudioSource()/setVideoSource() but before prepare().
447     *
448     * <p>It is recommended to always use 3GP format when using the H.263
449     * video encoder and AMR audio encoder. Using an MPEG-4 container format
450     * may confuse some desktop players.</p>
451     *
452     * @param output_format the output format to use. The output format
453     * needs to be specified before setting recording-parameters or encoders.
454     * @throws IllegalStateException if it is called after prepare() or before
455     * setAudioSource()/setVideoSource().
456     * @see android.media.MediaRecorder.OutputFormat
457     */
458    public native void setOutputFormat(int output_format)
459            throws IllegalStateException;
460
461    /**
462     * Sets the width and height of the video to be captured.  Must be called
463     * after setVideoSource(). Call this after setOutFormat() but before
464     * prepare().
465     *
466     * @param width the width of the video to be captured
467     * @param height the height of the video to be captured
468     * @throws IllegalStateException if it is called after
469     * prepare() or before setOutputFormat()
470     */
471    public native void setVideoSize(int width, int height)
472            throws IllegalStateException;
473
474    /**
475     * Sets the frame rate of the video to be captured.  Must be called
476     * after setVideoSource(). Call this after setOutFormat() but before
477     * prepare().
478     *
479     * @param rate the number of frames per second of video to capture
480     * @throws IllegalStateException if it is called after
481     * prepare() or before setOutputFormat().
482     *
483     * NOTE: On some devices that have auto-frame rate, this sets the
484     * maximum frame rate, not a constant frame rate. Actual frame rate
485     * will vary according to lighting conditions.
486     */
487    public native void setVideoFrameRate(int rate) throws IllegalStateException;
488
489    /**
490     * Sets the maximum duration (in ms) of the recording session.
491     * Call this after setOutFormat() but before prepare().
492     * After recording reaches the specified duration, a notification
493     * will be sent to the {@link android.media.MediaRecorder.OnInfoListener}
494     * with a "what" code of {@link #MEDIA_RECORDER_INFO_MAX_DURATION_REACHED}
495     * and recording will be stopped. Stopping happens asynchronously, there
496     * is no guarantee that the recorder will have stopped by the time the
497     * listener is notified.
498     *
499     * @param max_duration_ms the maximum duration in ms (if zero or negative, disables the duration limit)
500     *
501     */
502    public native void setMaxDuration(int max_duration_ms) throws IllegalArgumentException;
503
504    /**
505     * Sets the maximum filesize (in bytes) of the recording session.
506     * Call this after setOutFormat() but before prepare().
507     * After recording reaches the specified filesize, a notification
508     * will be sent to the {@link android.media.MediaRecorder.OnInfoListener}
509     * with a "what" code of {@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED}
510     * and recording will be stopped. Stopping happens asynchronously, there
511     * is no guarantee that the recorder will have stopped by the time the
512     * listener is notified.
513     *
514     * @param max_filesize_bytes the maximum filesize in bytes (if zero or negative, disables the limit)
515     *
516     */
517    public native void setMaxFileSize(long max_filesize_bytes) throws IllegalArgumentException;
518
519    /**
520     * Sets the audio encoder to be used for recording. If this method is not
521     * called, the output file will not contain an audio track. Call this after
522     * setOutputFormat() but before prepare().
523     *
524     * @param audio_encoder the audio encoder to use.
525     * @throws IllegalStateException if it is called before
526     * setOutputFormat() or after prepare().
527     * @see android.media.MediaRecorder.AudioEncoder
528     */
529    public native void setAudioEncoder(int audio_encoder)
530            throws IllegalStateException;
531
532    /**
533     * Sets the video encoder to be used for recording. If this method is not
534     * called, the output file will not contain an video track. Call this after
535     * setOutputFormat() and before prepare().
536     *
537     * @param video_encoder the video encoder to use.
538     * @throws IllegalStateException if it is called before
539     * setOutputFormat() or after prepare()
540     * @see android.media.MediaRecorder.VideoEncoder
541     */
542    public native void setVideoEncoder(int video_encoder)
543            throws IllegalStateException;
544
545    /**
546     * Sets the audio sampling rate for recording. Call this method before prepare().
547     * Prepare() may perform additional checks on the parameter to make sure whether
548     * the specified audio sampling rate is applicable. The sampling rate really depends
549     * on the format for the audio recording, as well as the capabilities of the platform.
550     * For instance, the sampling rate supported by AAC audio coding standard ranges
551     * from 8 to 96 kHz, the sampling rate supported by AMRNB is 8kHz, and the sampling
552     * rate supported by AMRWB is 16kHz. Please consult with the related audio coding
553     * standard for the supported audio sampling rate.
554     *
555     * @param samplingRate the sampling rate for audio in samples per second.
556     */
557    public void setAudioSamplingRate(int samplingRate) {
558        if (samplingRate <= 0) {
559            throw new IllegalArgumentException("Audio sampling rate is not positive");
560        }
561        setParameter("audio-param-sampling-rate=" + samplingRate);
562    }
563
564    /**
565     * Sets the number of audio channels for recording. Call this method before prepare().
566     * Prepare() may perform additional checks on the parameter to make sure whether the
567     * specified number of audio channels are applicable.
568     *
569     * @param numChannels the number of audio channels. Usually it is either 1 (mono) or 2
570     * (stereo).
571     */
572    public void setAudioChannels(int numChannels) {
573        if (numChannels <= 0) {
574            throw new IllegalArgumentException("Number of channels is not positive");
575        }
576        setParameter("audio-param-number-of-channels=" + numChannels);
577    }
578
579    /**
580     * Sets the audio encoding bit rate for recording. Call this method before prepare().
581     * Prepare() may perform additional checks on the parameter to make sure whether the
582     * specified bit rate is applicable, and sometimes the passed bitRate will be clipped
583     * internally to ensure the audio recording can proceed smoothly based on the
584     * capabilities of the platform.
585     *
586     * @param bitRate the audio encoding bit rate in bits per second.
587     */
588    public void setAudioEncodingBitRate(int bitRate) {
589        if (bitRate <= 0) {
590            throw new IllegalArgumentException("Audio encoding bit rate is not positive");
591        }
592        setParameter("audio-param-encoding-bitrate=" + bitRate);
593    }
594
595    /**
596     * Sets the video encoding bit rate for recording. Call this method before prepare().
597     * Prepare() may perform additional checks on the parameter to make sure whether the
598     * specified bit rate is applicable, and sometimes the passed bitRate will be
599     * clipped internally to ensure the video recording can proceed smoothly based on
600     * the capabilities of the platform.
601     *
602     * @param bitRate the video encoding bit rate in bits per second.
603     */
604    public void setVideoEncodingBitRate(int bitRate) {
605        if (bitRate <= 0) {
606            throw new IllegalArgumentException("Video encoding bit rate is not positive");
607        }
608        setParameter("video-param-encoding-bitrate=" + bitRate);
609    }
610
611    /**
612     * Currently not implemented. It does nothing.
613     * @deprecated Time lapse mode video recording using camera still image capture
614     * is not desirable, and will not be supported.
615     * @hide
616     */
617    public void setAuxiliaryOutputFile(FileDescriptor fd)
618    {
619        Log.w(TAG, "setAuxiliaryOutputFile(FileDescriptor) is no longer supported.");
620    }
621
622    /**
623     * Currently not implemented. It does nothing.
624     * @deprecated Time lapse mode video recording using camera still image capture
625     * is not desirable, and will not be supported.
626     * @hide
627     */
628    public void setAuxiliaryOutputFile(String path)
629    {
630        Log.w(TAG, "setAuxiliaryOutputFile(String) is no longer supported.");
631    }
632
633    /**
634     * Pass in the file descriptor of the file to be written. Call this after
635     * setOutputFormat() but before prepare().
636     *
637     * @param fd an open file descriptor to be written into.
638     * @throws IllegalStateException if it is called before
639     * setOutputFormat() or after prepare()
640     */
641    public void setOutputFile(FileDescriptor fd) throws IllegalStateException
642    {
643        mPath = null;
644        mFd = fd;
645    }
646
647    /**
648     * Sets the path of the output file to be produced. Call this after
649     * setOutputFormat() but before prepare().
650     *
651     * @param path The pathname to use.
652     * @throws IllegalStateException if it is called before
653     * setOutputFormat() or after prepare()
654     */
655    public void setOutputFile(String path) throws IllegalStateException
656    {
657        mFd = null;
658        mPath = path;
659    }
660
661    // native implementation
662    private native void _setOutputFile(FileDescriptor fd, long offset, long length)
663        throws IllegalStateException, IOException;
664    private native void _prepare() throws IllegalStateException, IOException;
665
666    /**
667     * Prepares the recorder to begin capturing and encoding data. This method
668     * must be called after setting up the desired audio and video sources,
669     * encoders, file format, etc., but before start().
670     *
671     * @throws IllegalStateException if it is called after
672     * start() or before setOutputFormat().
673     * @throws IOException if prepare fails otherwise.
674     */
675    public void prepare() throws IllegalStateException, IOException
676    {
677        if (mPath != null) {
678            FileOutputStream fos = new FileOutputStream(mPath);
679            try {
680                _setOutputFile(fos.getFD(), 0, 0);
681            } finally {
682                fos.close();
683            }
684        } else if (mFd != null) {
685            _setOutputFile(mFd, 0, 0);
686        } else {
687            throw new IOException("No valid output file");
688        }
689
690        _prepare();
691    }
692
693    /**
694     * Begins capturing and encoding data to the file specified with
695     * setOutputFile(). Call this after prepare().
696     *
697     * <p>Since API level 13, if applications set a camera via
698     * {@link #setCamera(Camera)}, the apps can use the camera after this method
699     * call. The apps do not need to lock the camera again. However, if this
700     * method fails, the apps should still lock the camera back. The apps should
701     * not start another recording session during recording.
702     *
703     * @throws IllegalStateException if it is called before
704     * prepare().
705     */
706    public native void start() throws IllegalStateException;
707
708    /**
709     * Stops recording. Call this after start(). Once recording is stopped,
710     * you will have to configure it again as if it has just been constructed.
711     * Note that a RuntimeException is intentionally thrown to the
712     * application, if no valid audio/video data has been received when stop()
713     * is called. This happens if stop() is called immediately after
714     * start(). The failure lets the application take action accordingly to
715     * clean up the output file (delete the output file, for instance), since
716     * the output file is not properly constructed when this happens.
717     *
718     * @throws IllegalStateException if it is called before start()
719     */
720    public native void stop() throws IllegalStateException;
721
722    /**
723     * Restarts the MediaRecorder to its idle state. After calling
724     * this method, you will have to configure it again as if it had just been
725     * constructed.
726     */
727    public void reset() {
728        native_reset();
729
730        // make sure none of the listeners get called anymore
731        mEventHandler.removeCallbacksAndMessages(null);
732    }
733
734    private native void native_reset();
735
736    /**
737     * Returns the maximum absolute amplitude that was sampled since the last
738     * call to this method. Call this only after the setAudioSource().
739     *
740     * @return the maximum absolute amplitude measured since the last call, or
741     * 0 when called for the first time
742     * @throws IllegalStateException if it is called before
743     * the audio source has been set.
744     */
745    public native int getMaxAmplitude() throws IllegalStateException;
746
747    /* Do not change this value without updating its counterpart
748     * in include/media/mediarecorder.h or mediaplayer.h!
749     */
750    /** Unspecified media recorder error.
751     * @see android.media.MediaRecorder.OnErrorListener
752     */
753    public static final int MEDIA_RECORDER_ERROR_UNKNOWN = 1;
754    /** Media server died. In this case, the application must release the
755     * MediaRecorder object and instantiate a new one.
756     * @see android.media.MediaRecorder.OnErrorListener
757     */
758    public static final int MEDIA_ERROR_SERVER_DIED = 100;
759
760    /**
761     * Interface definition for a callback to be invoked when an error
762     * occurs while recording.
763     */
764    public interface OnErrorListener
765    {
766        /**
767         * Called when an error occurs while recording.
768         *
769         * @param mr the MediaRecorder that encountered the error
770         * @param what    the type of error that has occurred:
771         * <ul>
772         * <li>{@link #MEDIA_RECORDER_ERROR_UNKNOWN}
773         * <li>{@link #MEDIA_ERROR_SERVER_DIED}
774         * </ul>
775         * @param extra   an extra code, specific to the error type
776         */
777        void onError(MediaRecorder mr, int what, int extra);
778    }
779
780    /**
781     * Register a callback to be invoked when an error occurs while
782     * recording.
783     *
784     * @param l the callback that will be run
785     */
786    public void setOnErrorListener(OnErrorListener l)
787    {
788        mOnErrorListener = l;
789    }
790
791    /* Do not change these values without updating their counterparts
792     * in include/media/mediarecorder.h!
793     */
794    /** Unspecified media recorder error.
795     * @see android.media.MediaRecorder.OnInfoListener
796     */
797    public static final int MEDIA_RECORDER_INFO_UNKNOWN              = 1;
798    /** A maximum duration had been setup and has now been reached.
799     * @see android.media.MediaRecorder.OnInfoListener
800     */
801    public static final int MEDIA_RECORDER_INFO_MAX_DURATION_REACHED = 800;
802    /** A maximum filesize had been setup and has now been reached.
803     * @see android.media.MediaRecorder.OnInfoListener
804     */
805    public static final int MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED = 801;
806
807    /** informational events for individual tracks, for testing purpose.
808     * The track informational event usually contains two parts in the ext1
809     * arg of the onInfo() callback: bit 31-28 contains the track id; and
810     * the rest of the 28 bits contains the informational event defined here.
811     * For example, ext1 = (1 << 28 | MEDIA_RECORDER_TRACK_INFO_TYPE) if the
812     * track id is 1 for informational event MEDIA_RECORDER_TRACK_INFO_TYPE;
813     * while ext1 = (0 << 28 | MEDIA_RECORDER_TRACK_INFO_TYPE) if the track
814     * id is 0 for informational event MEDIA_RECORDER_TRACK_INFO_TYPE. The
815     * application should extract the track id and the type of informational
816     * event from ext1, accordingly.
817     *
818     * FIXME:
819     * Please update the comment for onInfo also when these
820     * events are unhidden so that application knows how to extract the track
821     * id and the informational event type from onInfo callback.
822     *
823     * {@hide}
824     */
825    public static final int MEDIA_RECORDER_TRACK_INFO_LIST_START        = 1000;
826    /** Signal the completion of the track for the recording session.
827     * {@hide}
828     */
829    public static final int MEDIA_RECORDER_TRACK_INFO_COMPLETION_STATUS = 1000;
830    /** Indicate the recording progress in time (ms) during recording.
831     * {@hide}
832     */
833    public static final int MEDIA_RECORDER_TRACK_INFO_PROGRESS_IN_TIME  = 1001;
834    /** Indicate the track type: 0 for Audio and 1 for Video.
835     * {@hide}
836     */
837    public static final int MEDIA_RECORDER_TRACK_INFO_TYPE              = 1002;
838    /** Provide the track duration information.
839     * {@hide}
840     */
841    public static final int MEDIA_RECORDER_TRACK_INFO_DURATION_MS       = 1003;
842    /** Provide the max chunk duration in time (ms) for the given track.
843     * {@hide}
844     */
845    public static final int MEDIA_RECORDER_TRACK_INFO_MAX_CHUNK_DUR_MS  = 1004;
846    /** Provide the total number of recordd frames.
847     * {@hide}
848     */
849    public static final int MEDIA_RECORDER_TRACK_INFO_ENCODED_FRAMES    = 1005;
850    /** Provide the max spacing between neighboring chunks for the given track.
851     * {@hide}
852     */
853    public static final int MEDIA_RECORDER_TRACK_INTER_CHUNK_TIME_MS    = 1006;
854    /** Provide the elapsed time measuring from the start of the recording
855     * till the first output frame of the given track is received, excluding
856     * any intentional start time offset of a recording session for the
857     * purpose of eliminating the recording sound in the recorded file.
858     * {@hide}
859     */
860    public static final int MEDIA_RECORDER_TRACK_INFO_INITIAL_DELAY_MS  = 1007;
861    /** Provide the start time difference (delay) betweeen this track and
862     * the start of the movie.
863     * {@hide}
864     */
865    public static final int MEDIA_RECORDER_TRACK_INFO_START_OFFSET_MS   = 1008;
866    /** Provide the total number of data (in kilo-bytes) encoded.
867     * {@hide}
868     */
869    public static final int MEDIA_RECORDER_TRACK_INFO_DATA_KBYTES       = 1009;
870    /**
871     * {@hide}
872     */
873    public static final int MEDIA_RECORDER_TRACK_INFO_LIST_END          = 2000;
874
875
876    /**
877     * Interface definition for a callback to be invoked when an error
878     * occurs while recording.
879     */
880    public interface OnInfoListener
881    {
882        /**
883         * Called when an error occurs while recording.
884         *
885         * @param mr the MediaRecorder that encountered the error
886         * @param what    the type of error that has occurred:
887         * <ul>
888         * <li>{@link #MEDIA_RECORDER_INFO_UNKNOWN}
889         * <li>{@link #MEDIA_RECORDER_INFO_MAX_DURATION_REACHED}
890         * <li>{@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED}
891         * </ul>
892         * @param extra   an extra code, specific to the error type
893         */
894        void onInfo(MediaRecorder mr, int what, int extra);
895    }
896
897    /**
898     * Register a callback to be invoked when an informational event occurs while
899     * recording.
900     *
901     * @param listener the callback that will be run
902     */
903    public void setOnInfoListener(OnInfoListener listener)
904    {
905        mOnInfoListener = listener;
906    }
907
908    private class EventHandler extends Handler
909    {
910        private MediaRecorder mMediaRecorder;
911
912        public EventHandler(MediaRecorder mr, Looper looper) {
913            super(looper);
914            mMediaRecorder = mr;
915        }
916
917        /* Do not change these values without updating their counterparts
918         * in include/media/mediarecorder.h!
919         */
920        private static final int MEDIA_RECORDER_EVENT_LIST_START = 1;
921        private static final int MEDIA_RECORDER_EVENT_ERROR      = 1;
922        private static final int MEDIA_RECORDER_EVENT_INFO       = 2;
923        private static final int MEDIA_RECORDER_EVENT_LIST_END   = 99;
924
925        /* Events related to individual tracks */
926        private static final int MEDIA_RECORDER_TRACK_EVENT_LIST_START = 100;
927        private static final int MEDIA_RECORDER_TRACK_EVENT_ERROR      = 100;
928        private static final int MEDIA_RECORDER_TRACK_EVENT_INFO       = 101;
929        private static final int MEDIA_RECORDER_TRACK_EVENT_LIST_END   = 1000;
930
931
932        @Override
933        public void handleMessage(Message msg) {
934            if (mMediaRecorder.mNativeContext == 0) {
935                Log.w(TAG, "mediarecorder went away with unhandled events");
936                return;
937            }
938            switch(msg.what) {
939            case MEDIA_RECORDER_EVENT_ERROR:
940            case MEDIA_RECORDER_TRACK_EVENT_ERROR:
941                if (mOnErrorListener != null)
942                    mOnErrorListener.onError(mMediaRecorder, msg.arg1, msg.arg2);
943
944                return;
945
946            case MEDIA_RECORDER_EVENT_INFO:
947            case MEDIA_RECORDER_TRACK_EVENT_INFO:
948                if (mOnInfoListener != null)
949                    mOnInfoListener.onInfo(mMediaRecorder, msg.arg1, msg.arg2);
950
951                return;
952
953            default:
954                Log.e(TAG, "Unknown message type " + msg.what);
955                return;
956            }
957        }
958    }
959
960    /**
961     * Called from native code when an interesting event happens.  This method
962     * just uses the EventHandler system to post the event back to the main app thread.
963     * We use a weak reference to the original MediaRecorder object so that the native
964     * code is safe from the object disappearing from underneath it.  (This is
965     * the cookie passed to native_setup().)
966     */
967    private static void postEventFromNative(Object mediarecorder_ref,
968                                            int what, int arg1, int arg2, Object obj)
969    {
970        MediaRecorder mr = (MediaRecorder)((WeakReference)mediarecorder_ref).get();
971        if (mr == null) {
972            return;
973        }
974
975        if (mr.mEventHandler != null) {
976            Message m = mr.mEventHandler.obtainMessage(what, arg1, arg2, obj);
977            mr.mEventHandler.sendMessage(m);
978        }
979    }
980
981    /**
982     * Releases resources associated with this MediaRecorder object.
983     * It is good practice to call this method when you're done
984     * using the MediaRecorder. In particular, whenever an Activity
985     * of an application is paused (its onPause() method is called),
986     * or stopped (its onStop() method is called), this method should be
987     * invoked to release the MediaRecorder object, unless the application
988     * has a special need to keep the object around. In addition to
989     * unnecessary resources (such as memory and instances of codecs)
990     * being held, failure to call this method immediately if a
991     * MediaRecorder object is no longer needed may also lead to
992     * continuous battery consumption for mobile devices, and recording
993     * failure for other applications if no multiple instances of the
994     * same codec are supported on a device. Even if multiple instances
995     * of the same codec are supported, some performance degradation
996     * may be expected when unnecessary multiple instances are used
997     * at the same time.
998     */
999    public native void release();
1000
1001    private static native final void native_init();
1002
1003    private native final void native_setup(Object mediarecorder_this,
1004            String clientName) throws IllegalStateException;
1005
1006    private native final void native_finalize();
1007
1008    private native void setParameter(String nameValuePair);
1009
1010    @Override
1011    protected void finalize() { native_finalize(); }
1012}
1013