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