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