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