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