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