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