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