MediaRecorder.java revision 2bcda90c0234f67f210a96f195b355493ca7d1ff
1/* 2 * Copyright (C) 2007 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.media; 18 19import android.hardware.Camera; 20import android.os.Handler; 21import android.os.Looper; 22import android.os.Message; 23import android.util.Log; 24import android.view.Surface; 25import java.io.IOException; 26import java.io.FileNotFoundException; 27import java.io.FileOutputStream; 28import java.io.FileDescriptor; 29import java.lang.ref.WeakReference; 30 31/** 32 * Used to record audio and video. The recording control is based on a 33 * simple state machine (see below). 34 * 35 * <p><img src="{@docRoot}images/mediarecorder_state_diagram.gif" border="0" /> 36 * </p> 37 * 38 * <p>A common case of using MediaRecorder to record audio works as follows: 39 * 40 * <pre>MediaRecorder recorder = new MediaRecorder(); 41 * recorder.setAudioSource(MediaRecorder.AudioSource.MIC); 42 * recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); 43 * recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); 44 * recorder.setOutputFile(PATH_NAME); 45 * recorder.prepare(); 46 * recorder.start(); // Recording is now started 47 * ... 48 * recorder.stop(); 49 * recorder.reset(); // You can reuse the object by going back to setAudioSource() step 50 * recorder.release(); // Now the object cannot be reused 51 * </pre> 52 * 53 * <p>See the <a href="{@docRoot}guide/topics/media/index.html">Audio and Video</a> 54 * documentation for additional help with using MediaRecorder. 55 */ 56public class MediaRecorder 57{ 58 static { 59 System.loadLibrary("media_jni"); 60 } 61 private final static String TAG = "MediaRecorder"; 62 63 // The two fields below are accessed by native methods 64 @SuppressWarnings("unused") 65 private int mNativeContext; 66 67 @SuppressWarnings("unused") 68 private Surface mSurface; 69 70 private String mPath; 71 private FileDescriptor mFd; 72 private EventHandler mEventHandler; 73 private OnErrorListener mOnErrorListener; 74 private OnInfoListener mOnInfoListener; 75 76 /** 77 * Default constructor. 78 */ 79 public MediaRecorder() { 80 81 Looper looper; 82 if ((looper = Looper.myLooper()) != null) { 83 mEventHandler = new EventHandler(this, looper); 84 } else if ((looper = Looper.getMainLooper()) != null) { 85 mEventHandler = new EventHandler(this, looper); 86 } else { 87 mEventHandler = null; 88 } 89 90 /* Native setup requires a weak reference to our object. 91 * It's easier to create it here than in C++. 92 */ 93 native_setup(new WeakReference<MediaRecorder>(this)); 94 } 95 96 /** 97 * Sets a Camera to use for recording. Use this function to switch 98 * quickly between preview and capture mode without a teardown of 99 * the camera object. Must call before prepare(). 100 * 101 * @param c the Camera to use for recording 102 */ 103 public native void setCamera(Camera c); 104 105 /** 106 * Sets a Surface to show a preview of recorded media (video). Calls this 107 * before prepare() to make sure that the desirable preview display is 108 * set. 109 * 110 * @param sv the Surface to use for the preview 111 */ 112 public void setPreviewDisplay(Surface sv) { 113 mSurface = sv; 114 } 115 116 /** 117 * Defines the audio source. These constants are used with 118 * {@link MediaRecorder#setAudioSource(int)}. 119 */ 120 public final class AudioSource { 121 /* Do not change these values without updating their counterparts 122 * in include/media/mediarecorder.h! 123 */ 124 private AudioSource() {} 125 public static final int DEFAULT = 0; 126 /** Microphone audio source */ 127 public static final int MIC = 1; 128 129 /** Voice call uplink (Tx) audio source */ 130 public static final int VOICE_UPLINK = 2; 131 132 /** Voice call downlink (Rx) audio source */ 133 public static final int VOICE_DOWNLINK = 3; 134 135 /** Voice call uplink + downlink audio source */ 136 public static final int VOICE_CALL = 4; 137 } 138 139 /** 140 * Defines the video source. These constants are used with 141 * {@link MediaRecorder#setVideoSource(int)}. 142 */ 143 public final class VideoSource { 144 /* Do not change these values without updating their counterparts 145 * in include/media/mediarecorder.h! 146 */ 147 private VideoSource() {} 148 public static final int DEFAULT = 0; 149 /** Camera video source */ 150 public static final int CAMERA = 1; 151 } 152 153 /** 154 * Defines the output format. These constants are used with 155 * {@link MediaRecorder#setOutputFormat(int)}. 156 */ 157 public final class OutputFormat { 158 /* Do not change these values without updating their counterparts 159 * in include/media/mediarecorder.h! 160 */ 161 private OutputFormat() {} 162 public static final int DEFAULT = 0; 163 /** 3GPP media file format*/ 164 public static final int THREE_GPP = 1; 165 /** MPEG4 media file format*/ 166 public static final int MPEG_4 = 2; 167 168 /** The following formats are audio only .aac or .amr formats **/ 169 /** @deprecated Deprecated in favor of AMR_NB */ 170 /** @todo change link when AMR_NB is exposed. Deprecated in favor of {@link MediaRecorder.OutputFormat#AMR_NB} */ 171 public static final int RAW_AMR = 3; 172 /** @hide AMR NB file format */ 173 public static final int AMR_NB = 3; 174 /** @hide AMR WB file format */ 175 public static final int AMR_WB = 4; 176 /** @hide AAC ADIF file format */ 177 public static final int AAC_ADIF = 5; 178 /** @hide AAC ADTS file format */ 179 public static final int AAC_ADTS = 6; 180 }; 181 182 /** 183 * Defines the audio encoding. These constants are used with 184 * {@link MediaRecorder#setAudioEncoder(int)}. 185 */ 186 public final class AudioEncoder { 187 /* Do not change these values without updating their counterparts 188 * in include/media/mediarecorder.h! 189 */ 190 private AudioEncoder() {} 191 public static final int DEFAULT = 0; 192 /** AMR (Narrowband) audio codec */ 193 public static final int AMR_NB = 1; 194 /** @hide AMR (Wideband) audio codec */ 195 public static final int AMR_WB = 2; 196 /** @hide AAC audio codec */ 197 public static final int AAC = 3; 198 /** @hide enhanced AAC audio codec */ 199 public static final int AAC_PLUS = 4; 200 /** @hide enhanced AAC plus audio codec */ 201 public static final int EAAC_PLUS = 5; 202 } 203 204 /** 205 * Defines the video encoding. These constants are used with 206 * {@link MediaRecorder#setVideoEncoder(int)}. 207 */ 208 public final class VideoEncoder { 209 /* Do not change these values without updating their counterparts 210 * in include/media/mediarecorder.h! 211 */ 212 private VideoEncoder() {} 213 public static final int DEFAULT = 0; 214 public static final int H263 = 1; 215 public static final int H264 = 2; 216 public static final int MPEG_4_SP = 3; 217 } 218 219 220 /** 221 * @hide Defines the audio sampling rate. This must be set before 222 * setAudioEncoder() or it will be ignored. 223 * This parameter is used with 224 * {@link MediaRecorder#setParameters(String)}. 225 */ 226 public final class AudioParamSamplingRate { 227 /* Do not change these values without updating their counterparts 228 * in include/media/mediarecorder.h! 229 */ 230 private AudioParamSamplingRate() {} 231 public static final String AUDIO_PARAM_SAMPLING_RATE_KEY = "audio-param-sampling-rate="; 232 } 233 234 /** 235 * @hide Defines the audio number of channels. This must be set before 236 * setAudioEncoder() or it will be ignored. 237 * This parameter is used with 238 * {@link MediaRecorder#setParameters(String)}. 239 */ 240 public final class AudioParamChannels { 241 /* Do not change these values without updating their counterparts 242 * in include/media/mediarecorder.h! 243 */ 244 private AudioParamChannels() {} 245 public static final String AUDIO_PARAM_NUMBER_OF_CHANNELS = "audio-param-number-of-channels="; 246 } 247 248 /** 249 * @hide Defines the audio encoding bitrate. This must be set before 250 * setAudioEncoder() or it will be ignored. 251 * This parameter is used with 252 * {@link MediaRecorder#setParameters(String)}. 253 */ 254 public final class AudioParamEncodingBitrate{ 255 private AudioParamEncodingBitrate() {} 256 public static final String AUDIO_PARAM_ENCODING_BITRATE = "audio-param-encoding-bitrate="; 257 } 258 259 /** 260 * Sets the audio source to be used for recording. If this method is not 261 * called, the output file will not contain an audio track. The source needs 262 * to be specified before setting recording-parameters or encoders. Call 263 * this only before setOutputFormat(). 264 * 265 * @param audio_source the audio source to use 266 * @throws IllegalStateException if it is called after setOutputFormat() 267 * @see android.media.MediaRecorder.AudioSource 268 */ 269 public native void setAudioSource(int audio_source) 270 throws IllegalStateException; 271 272 /** 273 * Gets the maximum value for audio sources. 274 * @see android.media.MediaRecorder.AudioSource 275 */ 276 public static final int getAudioSourceMax() { return AudioSource.VOICE_CALL; } 277 278 /** 279 * Sets the video source to be used for recording. If this method is not 280 * called, the output file will not contain an video track. The source needs 281 * to be specified before setting recording-parameters or encoders. Call 282 * this only before setOutputFormat(). 283 * 284 * @param video_source the video source to use 285 * @throws IllegalStateException if it is called after setOutputFormat() 286 * @see android.media.MediaRecorder.VideoSource 287 */ 288 public native void setVideoSource(int video_source) 289 throws IllegalStateException; 290 291 /** 292 * Sets the format of the output file produced during recording. Call this 293 * after setAudioSource()/setVideoSource() but before prepare(). 294 * 295 * <p>It is recommended to always use 3GP format when using the H.263 296 * video encoder and AMR audio encoder. Using an MPEG-4 container format 297 * may confuse some desktop players.</p> 298 * 299 * @param output_format the output format to use. The output format 300 * needs to be specified before setting recording-parameters or encoders. 301 * @throws IllegalStateException if it is called after prepare() or before 302 * setAudioSource()/setVideoSource(). 303 * @see android.media.MediaRecorder.OutputFormat 304 */ 305 public native void setOutputFormat(int output_format) 306 throws IllegalStateException; 307 308 /** 309 * Sets the width and height of the video to be captured. Must be called 310 * after setVideoSource(). Call this after setOutFormat() but before 311 * prepare(). 312 * 313 * @param width the width of the video to be captured 314 * @param height the height of the video to be captured 315 * @throws IllegalStateException if it is called after 316 * prepare() or before setOutputFormat() 317 */ 318 public native void setVideoSize(int width, int height) 319 throws IllegalStateException; 320 321 /** 322 * Sets the frame rate of the video to be captured. Must be called 323 * after setVideoSource(). Call this after setOutFormat() but before 324 * prepare(). 325 * 326 * @param rate the number of frames per second of video to capture 327 * @throws IllegalStateException if it is called after 328 * prepare() or before setOutputFormat(). 329 * 330 * NOTE: On some devices that have auto-frame rate, this sets the 331 * maximum frame rate, not a constant frame rate. Actual frame rate 332 * will vary according to lighting conditions. 333 */ 334 public native void setVideoFrameRate(int rate) throws IllegalStateException; 335 336 /** 337 * Sets the maximum duration (in ms) of the recording session. 338 * Call this after setOutFormat() but before prepare(). 339 * After recording reaches the specified duration, a notification 340 * will be sent to the {@link android.media.MediaRecorder.OnInfoListener} 341 * with a "what" code of {@link #MEDIA_RECORDER_INFO_MAX_DURATION_REACHED} 342 * and recording will be stopped. Stopping happens asynchronously, there 343 * is no guarantee that the recorder will have stopped by the time the 344 * listener is notified. 345 * 346 * @param max_duration_ms the maximum duration in ms (if zero or negative, disables the duration limit) 347 * 348 */ 349 public native void setMaxDuration(int max_duration_ms) throws IllegalArgumentException; 350 351 /** 352 * Sets the maximum filesize (in bytes) of the recording session. 353 * Call this after setOutFormat() but before prepare(). 354 * After recording reaches the specified filesize, a notification 355 * will be sent to the {@link android.media.MediaRecorder.OnInfoListener} 356 * with a "what" code of {@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED} 357 * and recording will be stopped. Stopping happens asynchronously, there 358 * is no guarantee that the recorder will have stopped by the time the 359 * listener is notified. 360 * 361 * @param max_filesize_bytes the maximum filesize in bytes (if zero or negative, disables the limit) 362 * 363 */ 364 public native void setMaxFileSize(long max_filesize_bytes) throws IllegalArgumentException; 365 366 /** 367 * Sets the audio encoder to be used for recording. If this method is not 368 * called, the output file will not contain an audio track. Call this after 369 * setOutputFormat() but before prepare(). 370 * 371 * @param audio_encoder the audio encoder to use. 372 * @throws IllegalStateException if it is called before 373 * setOutputFormat() or after prepare(). 374 * @see android.media.MediaRecorder.AudioEncoder 375 */ 376 public native void setAudioEncoder(int audio_encoder) 377 throws IllegalStateException; 378 379 /** 380 * Sets the video encoder to be used for recording. If this method is not 381 * called, the output file will not contain an video track. Call this after 382 * setOutputFormat() and before prepare(). 383 * 384 * @param video_encoder the video encoder to use. 385 * @throws IllegalStateException if it is called before 386 * setOutputFormat() or after prepare() 387 * @see android.media.MediaRecorder.VideoEncoder 388 */ 389 public native void setVideoEncoder(int video_encoder) 390 throws IllegalStateException; 391 392 /** 393 * @hide Sets a parameter in the author engine. 394 * 395 * @param params the parameter to set. 396 * @see android.media.MediaRecorder.AudioParamSamplingRate 397 * @see android.media.MediaRecorder.AudioParamChannels 398 * @see android.media.MediaRecorder.AudioParamEncodingBitrate 399 */ 400 public native void setParameters(String params); 401 402 /** 403 * Pass in the file descriptor of the file to be written. Call this after 404 * setOutputFormat() but before prepare(). 405 * 406 * @param fd an open file descriptor to be written into. 407 * @throws IllegalStateException if it is called before 408 * setOutputFormat() or after prepare() 409 */ 410 public void setOutputFile(FileDescriptor fd) throws IllegalStateException 411 { 412 mPath = null; 413 mFd = fd; 414 } 415 416 /** 417 * Sets the path of the output file to be produced. Call this after 418 * setOutputFormat() but before prepare(). 419 * 420 * @param path The pathname to use. 421 * @throws IllegalStateException if it is called before 422 * setOutputFormat() or after prepare() 423 */ 424 public void setOutputFile(String path) throws IllegalStateException 425 { 426 mFd = null; 427 mPath = path; 428 } 429 430 // native implementation 431 private native void _setOutputFile(FileDescriptor fd, long offset, long length) 432 throws IllegalStateException, IOException; 433 private native void _prepare() throws IllegalStateException, IOException; 434 435 /** 436 * Prepares the recorder to begin capturing and encoding data. This method 437 * must be called after setting up the desired audio and video sources, 438 * encoders, file format, etc., but before start(). 439 * 440 * @throws IllegalStateException if it is called after 441 * start() or before setOutputFormat(). 442 * @throws IOException if prepare fails otherwise. 443 */ 444 public void prepare() throws IllegalStateException, IOException 445 { 446 if (mPath != null) { 447 FileOutputStream fos = new FileOutputStream(mPath); 448 try { 449 _setOutputFile(fos.getFD(), 0, 0); 450 } finally { 451 fos.close(); 452 } 453 } else if (mFd != null) { 454 _setOutputFile(mFd, 0, 0); 455 } else { 456 throw new IOException("No valid output file"); 457 } 458 _prepare(); 459 } 460 461 /** 462 * Begins capturing and encoding data to the file specified with 463 * setOutputFile(). Call this after prepare(). 464 * 465 * @throws IllegalStateException if it is called before 466 * prepare(). 467 */ 468 public native void start() throws IllegalStateException; 469 470 /** 471 * Stops recording. Call this after start(). Once recording is stopped, 472 * you will have to configure it again as if it has just been constructed. 473 * 474 * @throws IllegalStateException if it is called before start() 475 */ 476 public native void stop() throws IllegalStateException; 477 478 /** 479 * Restarts the MediaRecorder to its idle state. After calling 480 * this method, you will have to configure it again as if it had just been 481 * constructed. 482 */ 483 public void reset() { 484 native_reset(); 485 486 // make sure none of the listeners get called anymore 487 mEventHandler.removeCallbacksAndMessages(null); 488 } 489 490 private native void native_reset(); 491 492 /** 493 * Returns the maximum absolute amplitude that was sampled since the last 494 * call to this method. Call this only after the setAudioSource(). 495 * 496 * @return the maximum absolute amplitude measured since the last call, or 497 * 0 when called for the first time 498 * @throws IllegalStateException if it is called before 499 * the audio source has been set. 500 */ 501 public native int getMaxAmplitude() throws IllegalStateException; 502 503 /* Do not change this value without updating its counterpart 504 * in include/media/mediarecorder.h! 505 */ 506 /** Unspecified media recorder error. 507 * @see android.media.MediaRecorder.OnErrorListener 508 */ 509 public static final int MEDIA_RECORDER_ERROR_UNKNOWN = 1; 510 511 /** 512 * Interface definition for a callback to be invoked when an error 513 * occurs while recording. 514 */ 515 public interface OnErrorListener 516 { 517 /** 518 * Called when an error occurs while recording. 519 * 520 * @param mr the MediaRecorder that encountered the error 521 * @param what the type of error that has occurred: 522 * <ul> 523 * <li>{@link #MEDIA_RECORDER_ERROR_UNKNOWN} 524 * </ul> 525 * @param extra an extra code, specific to the error type 526 */ 527 void onError(MediaRecorder mr, int what, int extra); 528 } 529 530 /** 531 * Register a callback to be invoked when an error occurs while 532 * recording. 533 * 534 * @param l the callback that will be run 535 */ 536 public void setOnErrorListener(OnErrorListener l) 537 { 538 mOnErrorListener = l; 539 } 540 541 /* Do not change these values without updating their counterparts 542 * in include/media/mediarecorder.h! 543 */ 544 /** Unspecified media recorder error. 545 * @see android.media.MediaRecorder.OnInfoListener 546 */ 547 public static final int MEDIA_RECORDER_INFO_UNKNOWN = 1; 548 /** A maximum duration had been setup and has now been reached. 549 * @see android.media.MediaRecorder.OnInfoListener 550 */ 551 public static final int MEDIA_RECORDER_INFO_MAX_DURATION_REACHED = 800; 552 /** A maximum filesize had been setup and has now been reached. 553 * @see android.media.MediaRecorder.OnInfoListener 554 */ 555 public static final int MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED = 801; 556 557 /** 558 * Interface definition for a callback to be invoked when an error 559 * occurs while recording. 560 */ 561 public interface OnInfoListener 562 { 563 /** 564 * Called when an error occurs while recording. 565 * 566 * @param mr the MediaRecorder that encountered the error 567 * @param what the type of error that has occurred: 568 * <ul> 569 * <li>{@link #MEDIA_RECORDER_INFO_UNKNOWN} 570 * <li>{@link #MEDIA_RECORDER_INFO_MAX_DURATION_REACHED} 571 * <li>{@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED} 572 * </ul> 573 * @param extra an extra code, specific to the error type 574 */ 575 void onInfo(MediaRecorder mr, int what, int extra); 576 } 577 578 /** 579 * Register a callback to be invoked when an informational event occurs while 580 * recording. 581 * 582 * @param listener the callback that will be run 583 */ 584 public void setOnInfoListener(OnInfoListener listener) 585 { 586 mOnInfoListener = listener; 587 } 588 589 private class EventHandler extends Handler 590 { 591 private MediaRecorder mMediaRecorder; 592 593 public EventHandler(MediaRecorder mr, Looper looper) { 594 super(looper); 595 mMediaRecorder = mr; 596 } 597 598 /* Do not change these values without updating their counterparts 599 * in include/media/mediarecorder.h! 600 */ 601 private static final int MEDIA_RECORDER_EVENT_ERROR = 1; 602 private static final int MEDIA_RECORDER_EVENT_INFO = 2; 603 604 @Override 605 public void handleMessage(Message msg) { 606 if (mMediaRecorder.mNativeContext == 0) { 607 Log.w(TAG, "mediarecorder went away with unhandled events"); 608 return; 609 } 610 switch(msg.what) { 611 case MEDIA_RECORDER_EVENT_ERROR: 612 if (mOnErrorListener != null) 613 mOnErrorListener.onError(mMediaRecorder, msg.arg1, msg.arg2); 614 615 return; 616 617 case MEDIA_RECORDER_EVENT_INFO: 618 if (mOnInfoListener != null) 619 mOnInfoListener.onInfo(mMediaRecorder, msg.arg1, msg.arg2); 620 621 return; 622 623 default: 624 Log.e(TAG, "Unknown message type " + msg.what); 625 return; 626 } 627 } 628 } 629 630 /** 631 * Called from native code when an interesting event happens. This method 632 * just uses the EventHandler system to post the event back to the main app thread. 633 * We use a weak reference to the original MediaRecorder object so that the native 634 * code is safe from the object disappearing from underneath it. (This is 635 * the cookie passed to native_setup().) 636 */ 637 private static void postEventFromNative(Object mediarecorder_ref, 638 int what, int arg1, int arg2, Object obj) 639 { 640 MediaRecorder mr = (MediaRecorder)((WeakReference)mediarecorder_ref).get(); 641 if (mr == null) { 642 return; 643 } 644 645 if (mr.mEventHandler != null) { 646 Message m = mr.mEventHandler.obtainMessage(what, arg1, arg2, obj); 647 mr.mEventHandler.sendMessage(m); 648 } 649 } 650 651 /** 652 * Releases resources associated with this MediaRecorder object. 653 * It is good practice to call this method when you're done 654 * using the MediaRecorder. 655 */ 656 public native void release(); 657 658 private native final void native_setup(Object mediarecorder_this) throws IllegalStateException; 659 660 private native final void native_finalize(); 661 662 @Override 663 protected void finalize() { native_finalize(); } 664} 665