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