MediaRecorder.java revision 0fc6bc4cac6391f048f0f2748b3e979effe0924b
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.hardware.Camera;
20import android.os.Handler;
21import android.os.Looper;
22import android.os.Message;
23import android.util.Log;
24import android.view.Surface;
25import java.io.IOException;
26import java.io.FileNotFoundException;
27import java.io.FileOutputStream;
28import java.io.FileDescriptor;
29import java.lang.ref.WeakReference;
30
31/**
32 * Used to record audio and video. The recording control is based on a
33 * simple state machine (see below).
34 *
35 * <p><img src="{@docRoot}images/mediarecorder_state_diagram.gif" border="0" />
36 * </p>
37 *
38 * <p>A common case of using MediaRecorder to record audio works as follows:
39 *
40 * <pre>MediaRecorder recorder = new MediaRecorder();
41 * recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
42 * recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
43 * recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
44 * recorder.setOutputFile(PATH_NAME);
45 * recorder.prepare();
46 * recorder.start();   // Recording is now started
47 * ...
48 * recorder.stop();
49 * recorder.reset();   // You can reuse the object by going back to setAudioSource() step
50 * recorder.release(); // Now the object cannot be reused
51 * </pre>
52 *
53 * <p>See the <a href="{@docRoot}guide/topics/media/index.html">Audio and Video</a>
54 * documentation for additional help with using MediaRecorder.
55 */
56public class MediaRecorder
57{
58    static {
59        System.loadLibrary("media_jni");
60        native_init();
61    }
62    private final static String TAG = "MediaRecorder";
63
64    // The two fields below are accessed by native methods
65    @SuppressWarnings("unused")
66    private int mNativeContext;
67
68    @SuppressWarnings("unused")
69    private Surface mSurface;
70
71    private String mPath;
72    private FileDescriptor mFd;
73    private EventHandler mEventHandler;
74    private OnErrorListener mOnErrorListener;
75    private OnInfoListener mOnInfoListener;
76
77    /**
78     * Default constructor.
79     */
80    public MediaRecorder() {
81
82        Looper looper;
83        if ((looper = Looper.myLooper()) != null) {
84            mEventHandler = new EventHandler(this, looper);
85        } else if ((looper = Looper.getMainLooper()) != null) {
86            mEventHandler = new EventHandler(this, looper);
87        } else {
88            mEventHandler = null;
89        }
90
91        /* Native setup requires a weak reference to our object.
92         * It's easier to create it here than in C++.
93         */
94        native_setup(new WeakReference<MediaRecorder>(this));
95    }
96
97    /**
98     * Sets a Camera to use for recording. Use this function to switch
99     * quickly between preview and capture mode without a teardown of
100     * the camera object. Must call before prepare().
101     *
102     * @param c the Camera to use for recording
103     */
104    public native void setCamera(Camera c);
105
106    /**
107     * Sets a Surface to show a preview of recorded media (video). Calls this
108     * before prepare() to make sure that the desirable preview display is
109     * set.
110     *
111     * @param sv the Surface to use for the preview
112     */
113    public void setPreviewDisplay(Surface sv) {
114        mSurface = sv;
115    }
116
117    /**
118     * Defines the audio source. These constants are used with
119     * {@link MediaRecorder#setAudioSource(int)}.
120     */
121    public final class AudioSource {
122      /* Do not change these values without updating their counterparts
123       * in include/media/mediarecorder.h!
124       */
125        private AudioSource() {}
126        public static final int DEFAULT = 0;
127        /** Microphone audio source */
128        public static final int MIC = 1;
129
130        /** Voice call uplink (Tx) audio source */
131        public static final int VOICE_UPLINK = 2;
132
133        /** Voice call downlink (Rx) audio source */
134        public static final int VOICE_DOWNLINK = 3;
135
136        /** Voice call uplink + downlink audio source */
137        public static final int VOICE_CALL = 4;
138
139        /** Microphone audio source with same orientation as camera if available, the main
140         *  device microphone otherwise */
141        public static final int CAMCORDER = 5;
142
143        /** Microphone audio source tuned for voice recognition if available, behaves like
144         *  {@link #DEFAULT} otherwise. */
145        public static final int VOICE_RECOGNITION = 6;
146    }
147
148    /**
149     * Defines the video source. These constants are used with
150     * {@link MediaRecorder#setVideoSource(int)}.
151     */
152    public final class VideoSource {
153      /* Do not change these values without updating their counterparts
154       * in include/media/mediarecorder.h!
155       */
156        private VideoSource() {}
157        public static final int DEFAULT = 0;
158        /** Camera video source */
159        public static final int CAMERA = 1;
160    }
161
162    /**
163     * Defines the output format. These constants are used with
164     * {@link MediaRecorder#setOutputFormat(int)}.
165     */
166    public final class OutputFormat {
167      /* Do not change these values without updating their counterparts
168       * in include/media/mediarecorder.h!
169       */
170        private OutputFormat() {}
171        public static final int DEFAULT = 0;
172        /** 3GPP media file format*/
173        public static final int THREE_GPP = 1;
174        /** MPEG4 media file format*/
175        public static final int MPEG_4 = 2;
176
177        /** The following formats are audio only .aac or .amr formats **/
178        /** @deprecated  Deprecated in favor of AMR_NB */
179        /** TODO: change link when AMR_NB is exposed. Deprecated in favor of MediaRecorder.OutputFormat.AMR_NB */
180        public static final int RAW_AMR = 3;
181        /** @hide AMR NB file format */
182        public static final int AMR_NB = 3;
183        /** @hide AMR WB file format */
184        public static final int AMR_WB = 4;
185        /** @hide AAC ADIF file format */
186        public static final int AAC_ADIF = 5;
187        /** @hide AAC ADTS file format */
188        public static final int AAC_ADTS = 6;
189    };
190
191    /**
192     * Defines the audio encoding. These constants are used with
193     * {@link MediaRecorder#setAudioEncoder(int)}.
194     */
195    public final class AudioEncoder {
196      /* Do not change these values without updating their counterparts
197       * in include/media/mediarecorder.h!
198       */
199        private AudioEncoder() {}
200        public static final int DEFAULT = 0;
201        /** AMR (Narrowband) audio codec */
202        public static final int AMR_NB = 1;
203        /** @hide AMR (Wideband) audio codec */
204        public static final int AMR_WB = 2;
205        /** @hide AAC audio codec */
206        public static final int AAC = 3;
207        /** @hide enhanced AAC audio codec */
208        public static final int AAC_PLUS = 4;
209        /** @hide enhanced AAC plus audio codec */
210        public static final int EAAC_PLUS = 5;
211    }
212
213    /**
214     * Defines the video encoding. These constants are used with
215     * {@link MediaRecorder#setVideoEncoder(int)}.
216     */
217    public final class VideoEncoder {
218      /* Do not change these values without updating their counterparts
219       * in include/media/mediarecorder.h!
220       */
221        private VideoEncoder() {}
222        public static final int DEFAULT = 0;
223        public static final int H263 = 1;
224        public static final int H264 = 2;
225        public static final int MPEG_4_SP = 3;
226    }
227
228    /**
229     * Sets the audio source to be used for recording. If this method is not
230     * called, the output file will not contain an audio track. The source needs
231     * to be specified before setting recording-parameters or encoders. Call
232     * this only before setOutputFormat().
233     *
234     * @param audio_source the audio source to use
235     * @throws IllegalStateException if it is called after setOutputFormat()
236     * @see android.media.MediaRecorder.AudioSource
237     */
238    public native void setAudioSource(int audio_source)
239            throws IllegalStateException;
240
241    /**
242     * Gets the maximum value for audio sources.
243     * @see android.media.MediaRecorder.AudioSource
244     */
245    public static final int getAudioSourceMax() { return AudioSource.VOICE_RECOGNITION; }
246
247    /**
248     * Sets the video source to be used for recording. If this method is not
249     * called, the output file will not contain an video track. The source needs
250     * to be specified before setting recording-parameters or encoders. Call
251     * this only before setOutputFormat().
252     *
253     * @param video_source the video source to use
254     * @throws IllegalStateException if it is called after setOutputFormat()
255     * @see android.media.MediaRecorder.VideoSource
256     */
257    public native void setVideoSource(int video_source)
258            throws IllegalStateException;
259
260    /**
261     * Sets the format of the output file produced during recording. Call this
262     * after setAudioSource()/setVideoSource() but before prepare().
263     *
264     * <p>It is recommended to always use 3GP format when using the H.263
265     * video encoder and AMR audio encoder. Using an MPEG-4 container format
266     * may confuse some desktop players.</p>
267     *
268     * @param output_format the output format to use. The output format
269     * needs to be specified before setting recording-parameters or encoders.
270     * @throws IllegalStateException if it is called after prepare() or before
271     * setAudioSource()/setVideoSource().
272     * @see android.media.MediaRecorder.OutputFormat
273     */
274    public native void setOutputFormat(int output_format)
275            throws IllegalStateException;
276
277    /**
278     * Sets the width and height of the video to be captured.  Must be called
279     * after setVideoSource(). Call this after setOutFormat() but before
280     * prepare().
281     *
282     * @param width the width of the video to be captured
283     * @param height the height of the video to be captured
284     * @throws IllegalStateException if it is called after
285     * prepare() or before setOutputFormat()
286     */
287    public native void setVideoSize(int width, int height)
288            throws IllegalStateException;
289
290    /**
291     * Sets the frame rate of the video to be captured.  Must be called
292     * after setVideoSource(). Call this after setOutFormat() but before
293     * prepare().
294     *
295     * @param rate the number of frames per second of video to capture
296     * @throws IllegalStateException if it is called after
297     * prepare() or before setOutputFormat().
298     *
299     * NOTE: On some devices that have auto-frame rate, this sets the
300     * maximum frame rate, not a constant frame rate. Actual frame rate
301     * will vary according to lighting conditions.
302     */
303    public native void setVideoFrameRate(int rate) throws IllegalStateException;
304
305    /**
306     * Sets the maximum duration (in ms) of the recording session.
307     * Call this after setOutFormat() but before prepare().
308     * After recording reaches the specified duration, a notification
309     * will be sent to the {@link android.media.MediaRecorder.OnInfoListener}
310     * with a "what" code of {@link #MEDIA_RECORDER_INFO_MAX_DURATION_REACHED}
311     * and recording will be stopped. Stopping happens asynchronously, there
312     * is no guarantee that the recorder will have stopped by the time the
313     * listener is notified.
314     *
315     * @param max_duration_ms the maximum duration in ms (if zero or negative, disables the duration limit)
316     *
317     */
318    public native void setMaxDuration(int max_duration_ms) throws IllegalArgumentException;
319
320    /**
321     * Sets the maximum filesize (in bytes) of the recording session.
322     * Call this after setOutFormat() but before prepare().
323     * After recording reaches the specified filesize, a notification
324     * will be sent to the {@link android.media.MediaRecorder.OnInfoListener}
325     * with a "what" code of {@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED}
326     * and recording will be stopped. Stopping happens asynchronously, there
327     * is no guarantee that the recorder will have stopped by the time the
328     * listener is notified.
329     *
330     * @param max_filesize_bytes the maximum filesize in bytes (if zero or negative, disables the limit)
331     *
332     */
333    public native void setMaxFileSize(long max_filesize_bytes) throws IllegalArgumentException;
334
335    /**
336     * Sets the audio encoder to be used for recording. If this method is not
337     * called, the output file will not contain an audio track. Call this after
338     * setOutputFormat() but before prepare().
339     *
340     * @param audio_encoder the audio encoder to use.
341     * @throws IllegalStateException if it is called before
342     * setOutputFormat() or after prepare().
343     * @see android.media.MediaRecorder.AudioEncoder
344     */
345    public native void setAudioEncoder(int audio_encoder)
346            throws IllegalStateException;
347
348    /**
349     * Sets the video encoder to be used for recording. If this method is not
350     * called, the output file will not contain an video track. Call this after
351     * setOutputFormat() and before prepare().
352     *
353     * @param video_encoder the video encoder to use.
354     * @throws IllegalStateException if it is called before
355     * setOutputFormat() or after prepare()
356     * @see android.media.MediaRecorder.VideoEncoder
357     */
358    public native void setVideoEncoder(int video_encoder)
359            throws IllegalStateException;
360
361    /**
362     * Sets the audio sampling rate for recording. Call this method before prepare().
363     * Prepare() may perform additional checks on the parameter to make sure whether
364     * the specified audio sampling rate is applicable. The sampling rate really depends
365     * on the format for the audio recording, as well as the capabilities of the platform.
366     * For instance, the sampling rate supported by AAC audio coding standard ranges
367     * from 8 to 96 kHz. Please consult with the related audio coding standard for the
368     * supported audio sampling rate.
369     *
370     * @param samplingRate the sampling rate for audio in samples per second.
371     */
372    public void setAudioSamplingRate(int samplingRate) {
373        if (samplingRate <= 0) {
374            throw new IllegalArgumentException("Audio sampling rate is not positive");
375        }
376        setParameter(String.format("audio-param-sampling-rate=%d", samplingRate));
377    }
378
379    /**
380     * Sets the number of audio channels for recording. Call this method before prepare().
381     * Prepare() may perform additional checks on the parameter to make sure whether the
382     * specified number of audio channels are applicable.
383     *
384     * @param numChannels the number of audio channels. Usually it is either 1 (mono) or 2
385     * (stereo).
386     */
387    public void setAudioChannels(int numChannels) {
388        if (numChannels <= 0) {
389            throw new IllegalArgumentException("Number of channels is not positive");
390        }
391        setParameter(String.format("audio-param-number-of-channels=%d", numChannels));
392    }
393
394    /**
395     * Sets the audio encoding bit rate for recording. Call this method before prepare().
396     * Prepare() may perform additional checks on the parameter to make sure whether the
397     * specified bit rate is applicable, and sometimes the passed bitRate will be clipped
398     * internally to ensure the audio recording can proceed smoothly based on the
399     * capabilities of the platform.
400     *
401     * @param bitRate the audio encoding bit rate in bits per second.
402     */
403    public void setAudioEncodingBitRate(int bitRate) {
404        if (bitRate <= 0) {
405            throw new IllegalArgumentException("Audio encoding bit rate is not positive");
406        }
407        setParameter(String.format("audio-param-encoding-bitrate=%d", bitRate));
408    }
409
410    /**
411     * Sets the video encoding bit rate for recording. Call this method before prepare().
412     * Prepare() may perform additional checks on the parameter to make sure whether the
413     * specified bit rate is applicable, and sometimes the passed bitRate will be
414     * clipped internally to ensure the video recording can proceed smoothly based on
415     * the capabilities of the platform.
416     *
417     * @param bitRate the video encoding bit rate in bits per second.
418     */
419    public void setVideoEncodingBitRate(int bitRate) {
420        if (bitRate <= 0) {
421            throw new IllegalArgumentException("Video encoding bit rate is not positive");
422        }
423        setParameter(String.format("video-param-encoding-bitrate=%d", bitRate));
424    }
425
426    /**
427     * Pass in the file descriptor of the file to be written. Call this after
428     * setOutputFormat() but before prepare().
429     *
430     * @param fd an open file descriptor to be written into.
431     * @throws IllegalStateException if it is called before
432     * setOutputFormat() or after prepare()
433     */
434    public void setOutputFile(FileDescriptor fd) throws IllegalStateException
435    {
436        mPath = null;
437        mFd = fd;
438    }
439
440    /**
441     * Sets the path of the output file to be produced. Call this after
442     * setOutputFormat() but before prepare().
443     *
444     * @param path The pathname to use.
445     * @throws IllegalStateException if it is called before
446     * setOutputFormat() or after prepare()
447     */
448    public void setOutputFile(String path) throws IllegalStateException
449    {
450        mFd = null;
451        mPath = path;
452    }
453
454    // native implementation
455    private native void _setOutputFile(FileDescriptor fd, long offset, long length)
456        throws IllegalStateException, IOException;
457    private native void _prepare() throws IllegalStateException, IOException;
458
459    /**
460     * Prepares the recorder to begin capturing and encoding data. This method
461     * must be called after setting up the desired audio and video sources,
462     * encoders, file format, etc., but before start().
463     *
464     * @throws IllegalStateException if it is called after
465     * start() or before setOutputFormat().
466     * @throws IOException if prepare fails otherwise.
467     */
468    public void prepare() throws IllegalStateException, IOException
469    {
470        if (mPath != null) {
471            FileOutputStream fos = new FileOutputStream(mPath);
472            try {
473                _setOutputFile(fos.getFD(), 0, 0);
474            } finally {
475                fos.close();
476            }
477        } else if (mFd != null) {
478            _setOutputFile(mFd, 0, 0);
479        } else {
480            throw new IOException("No valid output file");
481        }
482        _prepare();
483    }
484
485    /**
486     * Begins capturing and encoding data to the file specified with
487     * setOutputFile(). Call this after prepare().
488     *
489     * @throws IllegalStateException if it is called before
490     * prepare().
491     */
492    public native void start() throws IllegalStateException;
493
494    /**
495     * Stops recording. Call this after start(). Once recording is stopped,
496     * you will have to configure it again as if it has just been constructed.
497     *
498     * @throws IllegalStateException if it is called before start()
499     */
500    public native void stop() throws IllegalStateException;
501
502    /**
503     * Restarts the MediaRecorder to its idle state. After calling
504     * this method, you will have to configure it again as if it had just been
505     * constructed.
506     */
507    public void reset() {
508        native_reset();
509
510        // make sure none of the listeners get called anymore
511        mEventHandler.removeCallbacksAndMessages(null);
512    }
513
514    private native void native_reset();
515
516    /**
517     * Returns the maximum absolute amplitude that was sampled since the last
518     * call to this method. Call this only after the setAudioSource().
519     *
520     * @return the maximum absolute amplitude measured since the last call, or
521     * 0 when called for the first time
522     * @throws IllegalStateException if it is called before
523     * the audio source has been set.
524     */
525    public native int getMaxAmplitude() throws IllegalStateException;
526
527    /* Do not change this value without updating its counterpart
528     * in include/media/mediarecorder.h!
529     */
530    /** Unspecified media recorder error.
531     * @see android.media.MediaRecorder.OnErrorListener
532     */
533    public static final int MEDIA_RECORDER_ERROR_UNKNOWN = 1;
534
535    /**
536     * Interface definition for a callback to be invoked when an error
537     * occurs while recording.
538     */
539    public interface OnErrorListener
540    {
541        /**
542         * Called when an error occurs while recording.
543         *
544         * @param mr the MediaRecorder that encountered the error
545         * @param what    the type of error that has occurred:
546         * <ul>
547         * <li>{@link #MEDIA_RECORDER_ERROR_UNKNOWN}
548         * </ul>
549         * @param extra   an extra code, specific to the error type
550         */
551        void onError(MediaRecorder mr, int what, int extra);
552    }
553
554    /**
555     * Register a callback to be invoked when an error occurs while
556     * recording.
557     *
558     * @param l the callback that will be run
559     */
560    public void setOnErrorListener(OnErrorListener l)
561    {
562        mOnErrorListener = l;
563    }
564
565    /* Do not change these values without updating their counterparts
566     * in include/media/mediarecorder.h!
567     */
568    /** Unspecified media recorder error.
569     * @see android.media.MediaRecorder.OnInfoListener
570     */
571    public static final int MEDIA_RECORDER_INFO_UNKNOWN              = 1;
572    /** A maximum duration had been setup and has now been reached.
573     * @see android.media.MediaRecorder.OnInfoListener
574     */
575    public static final int MEDIA_RECORDER_INFO_MAX_DURATION_REACHED = 800;
576    /** A maximum filesize had been setup and has now been reached.
577     * @see android.media.MediaRecorder.OnInfoListener
578     */
579    public static final int MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED = 801;
580
581    /**
582     * Interface definition for a callback to be invoked when an error
583     * occurs while recording.
584     */
585    public interface OnInfoListener
586    {
587        /**
588         * Called when an error occurs while recording.
589         *
590         * @param mr the MediaRecorder that encountered the error
591         * @param what    the type of error that has occurred:
592         * <ul>
593         * <li>{@link #MEDIA_RECORDER_INFO_UNKNOWN}
594         * <li>{@link #MEDIA_RECORDER_INFO_MAX_DURATION_REACHED}
595         * <li>{@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED}
596         * </ul>
597         * @param extra   an extra code, specific to the error type
598         */
599        void onInfo(MediaRecorder mr, int what, int extra);
600    }
601
602    /**
603     * Register a callback to be invoked when an informational event occurs while
604     * recording.
605     *
606     * @param listener the callback that will be run
607     */
608    public void setOnInfoListener(OnInfoListener listener)
609    {
610        mOnInfoListener = listener;
611    }
612
613    private class EventHandler extends Handler
614    {
615        private MediaRecorder mMediaRecorder;
616
617        public EventHandler(MediaRecorder mr, Looper looper) {
618            super(looper);
619            mMediaRecorder = mr;
620        }
621
622        /* Do not change these values without updating their counterparts
623         * in include/media/mediarecorder.h!
624         */
625        private static final int MEDIA_RECORDER_EVENT_ERROR = 1;
626        private static final int MEDIA_RECORDER_EVENT_INFO  = 2;
627
628        @Override
629        public void handleMessage(Message msg) {
630            if (mMediaRecorder.mNativeContext == 0) {
631                Log.w(TAG, "mediarecorder went away with unhandled events");
632                return;
633            }
634            switch(msg.what) {
635            case MEDIA_RECORDER_EVENT_ERROR:
636                if (mOnErrorListener != null)
637                    mOnErrorListener.onError(mMediaRecorder, msg.arg1, msg.arg2);
638
639                return;
640
641            case MEDIA_RECORDER_EVENT_INFO:
642                if (mOnInfoListener != null)
643                    mOnInfoListener.onInfo(mMediaRecorder, msg.arg1, msg.arg2);
644
645                return;
646
647            default:
648                Log.e(TAG, "Unknown message type " + msg.what);
649                return;
650            }
651        }
652    }
653
654    /**
655     * Called from native code when an interesting event happens.  This method
656     * just uses the EventHandler system to post the event back to the main app thread.
657     * We use a weak reference to the original MediaRecorder object so that the native
658     * code is safe from the object disappearing from underneath it.  (This is
659     * the cookie passed to native_setup().)
660     */
661    private static void postEventFromNative(Object mediarecorder_ref,
662                                            int what, int arg1, int arg2, Object obj)
663    {
664        MediaRecorder mr = (MediaRecorder)((WeakReference)mediarecorder_ref).get();
665        if (mr == null) {
666            return;
667        }
668
669        if (mr.mEventHandler != null) {
670            Message m = mr.mEventHandler.obtainMessage(what, arg1, arg2, obj);
671            mr.mEventHandler.sendMessage(m);
672        }
673    }
674
675    /**
676     * Releases resources associated with this MediaRecorder object.
677     * It is good practice to call this method when you're done
678     * using the MediaRecorder.
679     */
680    public native void release();
681
682    private static native final void native_init();
683
684    private native final void native_setup(Object mediarecorder_this) throws IllegalStateException;
685
686    private native final void native_finalize();
687
688    private native void setParameter(String nameValuePair);
689
690    @Override
691    protected void finalize() { native_finalize(); }
692}
693