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