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