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