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