MediaRecorder.java revision d1604c731330a74d1c8f160f045246a10e675899
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.media.CamcorderProfile; 20import android.hardware.Camera; 21import android.os.Handler; 22import android.os.Looper; 23import android.os.Message; 24import android.util.Log; 25import android.view.Surface; 26import java.io.IOException; 27import java.io.FileNotFoundException; 28import java.io.FileOutputStream; 29import java.io.FileDescriptor; 30import java.lang.ref.WeakReference; 31 32/** 33 * Used to record audio and video. The recording control is based on a 34 * simple state machine (see below). 35 * 36 * <p><img src="{@docRoot}images/mediarecorder_state_diagram.gif" border="0" /> 37 * </p> 38 * 39 * <p>A common case of using MediaRecorder to record audio works as follows: 40 * 41 * <pre>MediaRecorder recorder = new MediaRecorder(); 42 * recorder.setAudioSource(MediaRecorder.AudioSource.MIC); 43 * recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); 44 * recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); 45 * recorder.setOutputFile(PATH_NAME); 46 * recorder.prepare(); 47 * recorder.start(); // Recording is now started 48 * ... 49 * recorder.stop(); 50 * recorder.reset(); // You can reuse the object by going back to setAudioSource() step 51 * recorder.release(); // Now the object cannot be reused 52 * </pre> 53 * 54 * <p>See the <a href="{@docRoot}guide/topics/media/index.html">Audio and Video</a> 55 * documentation for additional help with using MediaRecorder. 56 * <p>Note: Currently, MediaRecorder does not work on the emulator. 57 */ 58public class MediaRecorder 59{ 60 static { 61 System.loadLibrary("media_jni"); 62 native_init(); 63 } 64 private final static String TAG = "MediaRecorder"; 65 66 // The two fields below are accessed by native methods 67 @SuppressWarnings("unused") 68 private int mNativeContext; 69 70 @SuppressWarnings("unused") 71 private Surface mSurface; 72 73 private String mPath; 74 private FileDescriptor mFd; 75 private boolean mPrepareAuxiliaryFile = false; 76 private String mPathAux; 77 private FileDescriptor mFdAux; 78 private EventHandler mEventHandler; 79 private OnErrorListener mOnErrorListener; 80 private OnInfoListener mOnInfoListener; 81 82 /** 83 * Default constructor. 84 */ 85 public MediaRecorder() { 86 87 Looper looper; 88 if ((looper = Looper.myLooper()) != null) { 89 mEventHandler = new EventHandler(this, looper); 90 } else if ((looper = Looper.getMainLooper()) != null) { 91 mEventHandler = new EventHandler(this, looper); 92 } else { 93 mEventHandler = null; 94 } 95 96 /* Native setup requires a weak reference to our object. 97 * It's easier to create it here than in C++. 98 */ 99 native_setup(new WeakReference<MediaRecorder>(this)); 100 } 101 102 /** 103 * Sets a Camera to use for recording. Use this function to switch 104 * quickly between preview and capture mode without a teardown of 105 * the camera object. Must call before prepare(). 106 * 107 * @param c the Camera to use for recording 108 */ 109 public native void setCamera(Camera c); 110 111 /** 112 * Sets a Surface to show a preview of recorded media (video). Calls this 113 * before prepare() to make sure that the desirable preview display is 114 * set. 115 * 116 * @param sv the Surface to use for the preview 117 */ 118 public void setPreviewDisplay(Surface sv) { 119 mSurface = sv; 120 } 121 122 /** 123 * Defines the audio source. These constants are used with 124 * {@link MediaRecorder#setAudioSource(int)}. 125 */ 126 public final class AudioSource { 127 /* Do not change these values without updating their counterparts 128 * in include/media/mediarecorder.h! 129 */ 130 private AudioSource() {} 131 public static final int DEFAULT = 0; 132 /** Microphone audio source */ 133 public static final int MIC = 1; 134 135 /** Voice call uplink (Tx) audio source */ 136 public static final int VOICE_UPLINK = 2; 137 138 /** Voice call downlink (Rx) audio source */ 139 public static final int VOICE_DOWNLINK = 3; 140 141 /** Voice call uplink + downlink audio source */ 142 public static final int VOICE_CALL = 4; 143 144 /** Microphone audio source with same orientation as camera if available, the main 145 * device microphone otherwise */ 146 public static final int CAMCORDER = 5; 147 148 /** Microphone audio source tuned for voice recognition if available, behaves like 149 * {@link #DEFAULT} otherwise. */ 150 public static final int VOICE_RECOGNITION = 6; 151 } 152 153 /** 154 * Defines the video source. These constants are used with 155 * {@link MediaRecorder#setVideoSource(int)}. 156 */ 157 public final class VideoSource { 158 /* Do not change these values without updating their counterparts 159 * in include/media/mediarecorder.h! 160 */ 161 private VideoSource() {} 162 public static final int DEFAULT = 0; 163 /** Camera video source */ 164 public static final int CAMERA = 1; 165 } 166 167 /** 168 * Defines the output format. These constants are used with 169 * {@link MediaRecorder#setOutputFormat(int)}. 170 */ 171 public final class OutputFormat { 172 /* Do not change these values without updating their counterparts 173 * in include/media/mediarecorder.h! 174 */ 175 private OutputFormat() {} 176 public static final int DEFAULT = 0; 177 /** 3GPP media file format*/ 178 public static final int THREE_GPP = 1; 179 /** MPEG4 media file format*/ 180 public static final int MPEG_4 = 2; 181 182 /** The following formats are audio only .aac or .amr formats **/ 183 /** @deprecated Deprecated in favor of AMR_NB */ 184 /** TODO: change link when AMR_NB is exposed. Deprecated in favor of MediaRecorder.OutputFormat.AMR_NB */ 185 public static final int RAW_AMR = 3; 186 /** @hide AMR NB file format */ 187 public static final int AMR_NB = 3; 188 /** @hide AMR WB file format */ 189 public static final int AMR_WB = 4; 190 /** @hide AAC ADIF file format */ 191 public static final int AAC_ADIF = 5; 192 /** @hide AAC ADTS file format */ 193 public static final int AAC_ADTS = 6; 194 195 /** @hide Stream over a socket, limited to a single stream */ 196 public static final int OUTPUT_FORMAT_RTP_AVP = 7; 197 198 /** @hide H.264/AAC data encapsulated in MPEG2/TS */ 199 public static final int OUTPUT_FORMAT_MPEG2TS = 8; 200 }; 201 202 /** 203 * Defines the audio encoding. These constants are used with 204 * {@link MediaRecorder#setAudioEncoder(int)}. 205 */ 206 public final class AudioEncoder { 207 /* Do not change these values without updating their counterparts 208 * in include/media/mediarecorder.h! 209 */ 210 private AudioEncoder() {} 211 public static final int DEFAULT = 0; 212 /** AMR (Narrowband) audio codec */ 213 public static final int AMR_NB = 1; 214 /** @hide AMR (Wideband) audio codec */ 215 public static final int AMR_WB = 2; 216 /** @hide AAC audio codec */ 217 public static final int AAC = 3; 218 /** @hide enhanced AAC audio codec */ 219 public static final int AAC_PLUS = 4; 220 /** @hide enhanced AAC plus audio codec */ 221 public static final int EAAC_PLUS = 5; 222 } 223 224 /** 225 * Defines the video encoding. These constants are used with 226 * {@link MediaRecorder#setVideoEncoder(int)}. 227 */ 228 public final class VideoEncoder { 229 /* Do not change these values without updating their counterparts 230 * in include/media/mediarecorder.h! 231 */ 232 private VideoEncoder() {} 233 public static final int DEFAULT = 0; 234 public static final int H263 = 1; 235 public static final int H264 = 2; 236 public static final int MPEG_4_SP = 3; 237 } 238 239 /** 240 * Sets the audio source to be used for recording. If this method is not 241 * called, the output file will not contain an audio track. The source needs 242 * to be specified before setting recording-parameters or encoders. Call 243 * this only before setOutputFormat(). 244 * 245 * @param audio_source the audio source to use 246 * @throws IllegalStateException if it is called after setOutputFormat() 247 * @see android.media.MediaRecorder.AudioSource 248 */ 249 public native void setAudioSource(int audio_source) 250 throws IllegalStateException; 251 252 /** 253 * Gets the maximum value for audio sources. 254 * @see android.media.MediaRecorder.AudioSource 255 */ 256 public static final int getAudioSourceMax() { return AudioSource.VOICE_RECOGNITION; } 257 258 /** 259 * Sets the video source to be used for recording. If this method is not 260 * called, the output file will not contain an video track. The source needs 261 * to be specified before setting recording-parameters or encoders. Call 262 * this only before setOutputFormat(). 263 * 264 * @param video_source the video source to use 265 * @throws IllegalStateException if it is called after setOutputFormat() 266 * @see android.media.MediaRecorder.VideoSource 267 */ 268 public native void setVideoSource(int video_source) 269 throws IllegalStateException; 270 271 /** 272 * Uses the settings from a CamcorderProfile object for recording. This method should 273 * be called after the video AND audio sources are set, and before setOutputFile(). 274 * 275 * @param profile the CamcorderProfile to use 276 * @see android.media.CamcorderProfile 277 */ 278 public void setProfile(CamcorderProfile profile) { 279 setOutputFormat(profile.fileFormat); 280 setVideoFrameRate(profile.videoFrameRate); 281 setVideoSize(profile.videoFrameWidth, profile.videoFrameHeight); 282 setVideoEncodingBitRate(profile.videoBitRate); 283 setVideoEncoder(profile.videoCodec); 284 if (profile.quality >= CamcorderProfile.QUALITY_TIME_LAPSE_LOW && 285 profile.quality <= CamcorderProfile.QUALITY_TIME_LAPSE_1080P) { 286 // Enable time lapse. Also don't set audio for time lapse. 287 setParameter(String.format("time-lapse-enable=1")); 288 } else { 289 setAudioEncodingBitRate(profile.audioBitRate); 290 setAudioChannels(profile.audioChannels); 291 setAudioSamplingRate(profile.audioSampleRate); 292 setAudioEncoder(profile.audioCodec); 293 } 294 } 295 296 /** 297 * Set video frame capture rate. This can be used to set a different video frame capture 298 * rate than the recorded video's playback rate. Currently this works only for time lapse mode. 299 * 300 * @param fps Rate at which frames should be captured in frames per second. 301 * The fps can go as low as desired. However the fastest fps will be limited by the hardware. 302 * For resolutions that can be captured by the video camera, the fastest fps can be computed using 303 * {@link android.hardware.Camera.Parameters#getPreviewFpsRange(int[])}. For higher 304 * resolutions the fastest fps may be more restrictive. 305 * Note that the recorder cannot guarantee that frames will be captured at the 306 * given rate due to camera/encoder limitations. However it tries to be as close as 307 * possible. 308 */ 309 public void setCaptureRate(double fps) { 310 double timeBetweenFrameCapture = 1 / fps; 311 int timeBetweenFrameCaptureMs = (int) (1000 * timeBetweenFrameCapture); 312 setParameter(String.format("time-between-time-lapse-frame-capture=%d", 313 timeBetweenFrameCaptureMs)); 314 } 315 316 /** 317 * Sets the orientation hint for output video playback. 318 * This method should be called before prepare(). This method will not 319 * trigger the source video frame to rotate during video recording, but to 320 * add a composition matrix containing the rotation angle in the output 321 * video if the output format is OutputFormat.THREE_GPP or 322 * OutputFormat.MPEG_4 so that a video player can choose the proper 323 * orientation for playback. Note that some video players may choose 324 * to ignore the compostion matrix in a video during playback. 325 * 326 * @param degrees the angle to be rotated clockwise in degrees. 327 * The supported angles are 0, 90, 180, and 270 degrees. 328 * @throws IllegalArgumentException if the angle is not supported. 329 * 330 */ 331 public void setOrientationHint(int degrees) { 332 if (degrees != 0 && 333 degrees != 90 && 334 degrees != 180 && 335 degrees != 270) { 336 throw new IllegalArgumentException("Unsupported angle: " + degrees); 337 } 338 setParameter(String.format("video-param-rotation-angle-degrees=%d", degrees)); 339 } 340 341 /** 342 * Sets the format of the output file produced during recording. Call this 343 * after setAudioSource()/setVideoSource() but before prepare(). 344 * 345 * <p>It is recommended to always use 3GP format when using the H.263 346 * video encoder and AMR audio encoder. Using an MPEG-4 container format 347 * may confuse some desktop players.</p> 348 * 349 * @param output_format the output format to use. The output format 350 * needs to be specified before setting recording-parameters or encoders. 351 * @throws IllegalStateException if it is called after prepare() or before 352 * setAudioSource()/setVideoSource(). 353 * @see android.media.MediaRecorder.OutputFormat 354 */ 355 public native void setOutputFormat(int output_format) 356 throws IllegalStateException; 357 358 /** 359 * Sets the width and height of the video to be captured. Must be called 360 * after setVideoSource(). Call this after setOutFormat() but before 361 * prepare(). 362 * 363 * @param width the width of the video to be captured 364 * @param height the height of the video to be captured 365 * @throws IllegalStateException if it is called after 366 * prepare() or before setOutputFormat() 367 */ 368 public native void setVideoSize(int width, int height) 369 throws IllegalStateException; 370 371 /** 372 * Sets the frame rate of the video to be captured. Must be called 373 * after setVideoSource(). Call this after setOutFormat() but before 374 * prepare(). 375 * 376 * @param rate the number of frames per second of video to capture 377 * @throws IllegalStateException if it is called after 378 * prepare() or before setOutputFormat(). 379 * 380 * NOTE: On some devices that have auto-frame rate, this sets the 381 * maximum frame rate, not a constant frame rate. Actual frame rate 382 * will vary according to lighting conditions. 383 */ 384 public native void setVideoFrameRate(int rate) throws IllegalStateException; 385 386 /** 387 * Sets the maximum duration (in ms) of the recording session. 388 * Call this after setOutFormat() but before prepare(). 389 * After recording reaches the specified duration, a notification 390 * will be sent to the {@link android.media.MediaRecorder.OnInfoListener} 391 * with a "what" code of {@link #MEDIA_RECORDER_INFO_MAX_DURATION_REACHED} 392 * and recording will be stopped. Stopping happens asynchronously, there 393 * is no guarantee that the recorder will have stopped by the time the 394 * listener is notified. 395 * 396 * @param max_duration_ms the maximum duration in ms (if zero or negative, disables the duration limit) 397 * 398 */ 399 public native void setMaxDuration(int max_duration_ms) throws IllegalArgumentException; 400 401 /** 402 * Sets the maximum filesize (in bytes) of the recording session. 403 * Call this after setOutFormat() but before prepare(). 404 * After recording reaches the specified filesize, a notification 405 * will be sent to the {@link android.media.MediaRecorder.OnInfoListener} 406 * with a "what" code of {@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED} 407 * and recording will be stopped. Stopping happens asynchronously, there 408 * is no guarantee that the recorder will have stopped by the time the 409 * listener is notified. 410 * 411 * @param max_filesize_bytes the maximum filesize in bytes (if zero or negative, disables the limit) 412 * 413 */ 414 public native void setMaxFileSize(long max_filesize_bytes) throws IllegalArgumentException; 415 416 /** 417 * Sets the audio encoder to be used for recording. If this method is not 418 * called, the output file will not contain an audio track. Call this after 419 * setOutputFormat() but before prepare(). 420 * 421 * @param audio_encoder the audio encoder to use. 422 * @throws IllegalStateException if it is called before 423 * setOutputFormat() or after prepare(). 424 * @see android.media.MediaRecorder.AudioEncoder 425 */ 426 public native void setAudioEncoder(int audio_encoder) 427 throws IllegalStateException; 428 429 /** 430 * Sets the video encoder to be used for recording. If this method is not 431 * called, the output file will not contain an video track. Call this after 432 * setOutputFormat() and before prepare(). 433 * 434 * @param video_encoder the video encoder to use. 435 * @throws IllegalStateException if it is called before 436 * setOutputFormat() or after prepare() 437 * @see android.media.MediaRecorder.VideoEncoder 438 */ 439 public native void setVideoEncoder(int video_encoder) 440 throws IllegalStateException; 441 442 /** 443 * Sets the audio sampling rate for recording. Call this method before prepare(). 444 * Prepare() may perform additional checks on the parameter to make sure whether 445 * the specified audio sampling rate is applicable. The sampling rate really depends 446 * on the format for the audio recording, as well as the capabilities of the platform. 447 * For instance, the sampling rate supported by AAC audio coding standard ranges 448 * from 8 to 96 kHz. Please consult with the related audio coding standard for the 449 * supported audio sampling rate. 450 * 451 * @param samplingRate the sampling rate for audio in samples per second. 452 */ 453 public void setAudioSamplingRate(int samplingRate) { 454 if (samplingRate <= 0) { 455 throw new IllegalArgumentException("Audio sampling rate is not positive"); 456 } 457 setParameter(String.format("audio-param-sampling-rate=%d", samplingRate)); 458 } 459 460 /** 461 * Sets the number of audio channels for recording. Call this method before prepare(). 462 * Prepare() may perform additional checks on the parameter to make sure whether the 463 * specified number of audio channels are applicable. 464 * 465 * @param numChannels the number of audio channels. Usually it is either 1 (mono) or 2 466 * (stereo). 467 */ 468 public void setAudioChannels(int numChannels) { 469 if (numChannels <= 0) { 470 throw new IllegalArgumentException("Number of channels is not positive"); 471 } 472 setParameter(String.format("audio-param-number-of-channels=%d", numChannels)); 473 } 474 475 /** 476 * Sets the audio encoding bit rate for recording. Call this method before prepare(). 477 * Prepare() may perform additional checks on the parameter to make sure whether the 478 * specified bit rate is applicable, and sometimes the passed bitRate will be clipped 479 * internally to ensure the audio recording can proceed smoothly based on the 480 * capabilities of the platform. 481 * 482 * @param bitRate the audio encoding bit rate in bits per second. 483 */ 484 public void setAudioEncodingBitRate(int bitRate) { 485 if (bitRate <= 0) { 486 throw new IllegalArgumentException("Audio encoding bit rate is not positive"); 487 } 488 setParameter(String.format("audio-param-encoding-bitrate=%d", bitRate)); 489 } 490 491 /** 492 * Sets the video encoding bit rate for recording. Call this method before prepare(). 493 * Prepare() may perform additional checks on the parameter to make sure whether the 494 * specified bit rate is applicable, and sometimes the passed bitRate will be 495 * clipped internally to ensure the video recording can proceed smoothly based on 496 * the capabilities of the platform. 497 * 498 * @param bitRate the video encoding bit rate in bits per second. 499 */ 500 public void setVideoEncodingBitRate(int bitRate) { 501 if (bitRate <= 0) { 502 throw new IllegalArgumentException("Video encoding bit rate is not positive"); 503 } 504 setParameter(String.format("video-param-encoding-bitrate=%d", bitRate)); 505 } 506 507 /** 508 * Sets the auxiliary time lapse video's resolution and bitrate. 509 * 510 * The auxiliary video's resolution and bitrate are determined by the CamcorderProfile 511 * quality level {@link android.media.CamcorderProfile#QUALITY_HIGH}. 512 */ 513 private void setAuxVideoParameters() { 514 CamcorderProfile profile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH); 515 setParameter(String.format("video-aux-param-width=%d", profile.videoFrameWidth)); 516 setParameter(String.format("video-aux-param-height=%d", profile.videoFrameHeight)); 517 setParameter(String.format("video-aux-param-encoding-bitrate=%d", profile.videoBitRate)); 518 } 519 520 /** 521 * Pass in the file descriptor for the auxiliary time lapse video. Call this before 522 * prepare(). 523 * 524 * Sets file descriptor and parameters for auxiliary time lapse video. Time lapse mode 525 * can capture video (using the still camera) at resolutions higher than that can be 526 * played back on the device. This function or 527 * {@link #setAuxiliaryOutputFile(String)} enable capture of a smaller video in 528 * parallel with the main time lapse video, which can be used to play back on the 529 * device. The smaller video is created by downsampling the main video. This call is 530 * optional and does not have to be called if parallel capture of a downsampled video 531 * is not desired. 532 * 533 * Note that while the main video resolution and bitrate is determined from the 534 * CamcorderProfile in {@link #setProfile(CamcorderProfile)}, the auxiliary video's 535 * resolution and bitrate are determined by the CamcorderProfile quality level 536 * {@link android.media.CamcorderProfile#QUALITY_HIGH}. All other encoding parameters 537 * remain the same for the main video and the auxiliary video. 538 * 539 * E.g. if the device supports the time lapse profile quality level 540 * {@link android.media.CamcorderProfile#QUALITY_TIME_LAPSE_1080P} but can playback at 541 * most 480p, the application might want to capture an auxiliary video of resolution 542 * 480p using this call. 543 * 544 * @param fd an open file descriptor to be written into. 545 */ 546 public void setAuxiliaryOutputFile(FileDescriptor fd) 547 { 548 mPrepareAuxiliaryFile = true; 549 mPathAux = null; 550 mFdAux = fd; 551 setAuxVideoParameters(); 552 } 553 554 /** 555 * Pass in the file path for the auxiliary time lapse video. Call this before 556 * prepare(). 557 * 558 * Sets file path and parameters for auxiliary time lapse video. Time lapse mode can 559 * capture video (using the still camera) at resolutions higher than that can be 560 * played back on the device. This function or 561 * {@link #setAuxiliaryOutputFile(FileDescriptor)} enable capture of a smaller 562 * video in parallel with the main time lapse video, which can be used to play back on 563 * the device. The smaller video is created by downsampling the main video. This call 564 * is optional and does not have to be called if parallel capture of a downsampled 565 * video is not desired. 566 * 567 * Note that while the main video resolution and bitrate is determined from the 568 * CamcorderProfile in {@link #setProfile(CamcorderProfile)}, the auxiliary video's 569 * resolution and bitrate are determined by the CamcorderProfile quality level 570 * {@link android.media.CamcorderProfile#QUALITY_HIGH}. All other encoding parameters 571 * remain the same for the main video and the auxiliary video. 572 * 573 * E.g. if the device supports the time lapse profile quality level 574 * {@link android.media.CamcorderProfile#QUALITY_TIME_LAPSE_1080P} but can playback at 575 * most 480p, the application might want to capture an auxiliary video of resolution 576 * 480p using this call. 577 * 578 * @param path The pathname to use. 579 */ 580 public void setAuxiliaryOutputFile(String path) 581 { 582 mPrepareAuxiliaryFile = true; 583 mFdAux = null; 584 mPathAux = path; 585 setAuxVideoParameters(); 586 } 587 588 /** 589 * Pass in the file descriptor of the file to be written. Call this after 590 * setOutputFormat() but before prepare(). 591 * 592 * @param fd an open file descriptor to be written into. 593 * @throws IllegalStateException if it is called before 594 * setOutputFormat() or after prepare() 595 */ 596 public void setOutputFile(FileDescriptor fd) throws IllegalStateException 597 { 598 mPath = null; 599 mFd = fd; 600 } 601 602 /** 603 * Sets the path of the output file to be produced. Call this after 604 * setOutputFormat() but before prepare(). 605 * 606 * @param path The pathname to use. 607 * @throws IllegalStateException if it is called before 608 * setOutputFormat() or after prepare() 609 */ 610 public void setOutputFile(String path) throws IllegalStateException 611 { 612 mFd = null; 613 mPath = path; 614 } 615 616 // native implementation 617 private native void _setOutputFile(FileDescriptor fd, long offset, long length) 618 throws IllegalStateException, IOException; 619 private native void _setOutputFileAux(FileDescriptor fd) 620 throws IllegalStateException, IOException; 621 private native void _prepare() throws IllegalStateException, IOException; 622 623 /** 624 * Prepares the recorder to begin capturing and encoding data. This method 625 * must be called after setting up the desired audio and video sources, 626 * encoders, file format, etc., but before start(). 627 * 628 * @throws IllegalStateException if it is called after 629 * start() or before setOutputFormat(). 630 * @throws IOException if prepare fails otherwise. 631 */ 632 public void prepare() throws IllegalStateException, IOException 633 { 634 if (mPath != null) { 635 FileOutputStream fos = new FileOutputStream(mPath); 636 try { 637 _setOutputFile(fos.getFD(), 0, 0); 638 } finally { 639 fos.close(); 640 } 641 } else if (mFd != null) { 642 _setOutputFile(mFd, 0, 0); 643 } else { 644 throw new IOException("No valid output file"); 645 } 646 647 if (mPrepareAuxiliaryFile) { 648 if (mPathAux != null) { 649 FileOutputStream fos = new FileOutputStream(mPathAux); 650 try { 651 _setOutputFileAux(fos.getFD()); 652 } finally { 653 fos.close(); 654 } 655 } else if (mFdAux != null) { 656 _setOutputFileAux(mFdAux); 657 } else { 658 throw new IOException("No valid output file"); 659 } 660 } 661 662 _prepare(); 663 } 664 665 /** 666 * Begins capturing and encoding data to the file specified with 667 * setOutputFile(). Call this after prepare(). 668 * 669 * @throws IllegalStateException if it is called before 670 * prepare(). 671 */ 672 public native void start() throws IllegalStateException; 673 674 /** 675 * Stops recording. Call this after start(). Once recording is stopped, 676 * you will have to configure it again as if it has just been constructed. 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 /** 762 * Interface definition for a callback to be invoked when an error 763 * occurs while recording. 764 */ 765 public interface OnInfoListener 766 { 767 /** 768 * Called when an error occurs while recording. 769 * 770 * @param mr the MediaRecorder that encountered the error 771 * @param what the type of error that has occurred: 772 * <ul> 773 * <li>{@link #MEDIA_RECORDER_INFO_UNKNOWN} 774 * <li>{@link #MEDIA_RECORDER_INFO_MAX_DURATION_REACHED} 775 * <li>{@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED} 776 * </ul> 777 * @param extra an extra code, specific to the error type 778 */ 779 void onInfo(MediaRecorder mr, int what, int extra); 780 } 781 782 /** 783 * Register a callback to be invoked when an informational event occurs while 784 * recording. 785 * 786 * @param listener the callback that will be run 787 */ 788 public void setOnInfoListener(OnInfoListener listener) 789 { 790 mOnInfoListener = listener; 791 } 792 793 private class EventHandler extends Handler 794 { 795 private MediaRecorder mMediaRecorder; 796 797 public EventHandler(MediaRecorder mr, Looper looper) { 798 super(looper); 799 mMediaRecorder = mr; 800 } 801 802 /* Do not change these values without updating their counterparts 803 * in include/media/mediarecorder.h! 804 */ 805 private static final int MEDIA_RECORDER_EVENT_ERROR = 1; 806 private static final int MEDIA_RECORDER_EVENT_INFO = 2; 807 808 @Override 809 public void handleMessage(Message msg) { 810 if (mMediaRecorder.mNativeContext == 0) { 811 Log.w(TAG, "mediarecorder went away with unhandled events"); 812 return; 813 } 814 switch(msg.what) { 815 case MEDIA_RECORDER_EVENT_ERROR: 816 if (mOnErrorListener != null) 817 mOnErrorListener.onError(mMediaRecorder, msg.arg1, msg.arg2); 818 819 return; 820 821 case MEDIA_RECORDER_EVENT_INFO: 822 if (mOnInfoListener != null) 823 mOnInfoListener.onInfo(mMediaRecorder, msg.arg1, msg.arg2); 824 825 return; 826 827 default: 828 Log.e(TAG, "Unknown message type " + msg.what); 829 return; 830 } 831 } 832 } 833 834 /** 835 * Called from native code when an interesting event happens. This method 836 * just uses the EventHandler system to post the event back to the main app thread. 837 * We use a weak reference to the original MediaRecorder object so that the native 838 * code is safe from the object disappearing from underneath it. (This is 839 * the cookie passed to native_setup().) 840 */ 841 private static void postEventFromNative(Object mediarecorder_ref, 842 int what, int arg1, int arg2, Object obj) 843 { 844 MediaRecorder mr = (MediaRecorder)((WeakReference)mediarecorder_ref).get(); 845 if (mr == null) { 846 return; 847 } 848 849 if (mr.mEventHandler != null) { 850 Message m = mr.mEventHandler.obtainMessage(what, arg1, arg2, obj); 851 mr.mEventHandler.sendMessage(m); 852 } 853 } 854 855 /** 856 * Releases resources associated with this MediaRecorder object. 857 * It is good practice to call this method when you're done 858 * using the MediaRecorder. 859 */ 860 public native void release(); 861 862 private static native final void native_init(); 863 864 private native final void native_setup(Object mediarecorder_this) throws IllegalStateException; 865 866 private native final void native_finalize(); 867 868 private native void setParameter(String nameValuePair); 869 870 @Override 871 protected void finalize() { native_finalize(); } 872} 873