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