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