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