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