MediaRecorder.java revision 4bc035a65cac177be9294e69f110497e3b6e34e6
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 /** Raw AMR file format */ 168 public static final int RAW_AMR = 3; 169 }; 170 171 /** 172 * Defines the audio encoding. These constants are used with 173 * {@link MediaRecorder#setAudioEncoder(int)}. 174 */ 175 public final class AudioEncoder { 176 /* Do not change these values without updating their counterparts 177 * in include/media/mediarecorder.h! 178 */ 179 private AudioEncoder() {} 180 public static final int DEFAULT = 0; 181 /** AMR (Narrowband) audio codec */ 182 public static final int AMR_NB = 1; 183 //public static final AAC = 2; currently unsupported 184 } 185 186 /** 187 * Defines the video encoding. These constants are used with 188 * {@link MediaRecorder#setVideoEncoder(int)}. 189 */ 190 public final class VideoEncoder { 191 /* Do not change these values without updating their counterparts 192 * in include/media/mediarecorder.h! 193 */ 194 private VideoEncoder() {} 195 public static final int DEFAULT = 0; 196 public static final int H263 = 1; 197 public static final int H264 = 2; 198 public static final int MPEG_4_SP = 3; 199 } 200 201 /** 202 * Sets the audio source to be used for recording. If this method is not 203 * called, the output file will not contain an audio track. The source needs 204 * to be specified before setting recording-parameters or encoders. Call 205 * this only before setOutputFormat(). 206 * 207 * @param audio_source the audio source to use 208 * @throws IllegalStateException if it is called after setOutputFormat() 209 * @see android.media.MediaRecorder.AudioSource 210 */ 211 public native void setAudioSource(int audio_source) 212 throws IllegalStateException; 213 214 /** 215 * Gets the maximum value for audio sources. 216 * @see android.media.MediaRecorder.AudioSource 217 */ 218 public static final int getAudioSourceMax() { return AudioSource.VOICE_CALL; } 219 220 /** 221 * Sets the video source to be used for recording. If this method is not 222 * called, the output file will not contain an video track. The source needs 223 * to be specified before setting recording-parameters or encoders. Call 224 * this only before setOutputFormat(). 225 * 226 * @param video_source the video source to use 227 * @throws IllegalStateException if it is called after setOutputFormat() 228 * @see android.media.MediaRecorder.VideoSource 229 */ 230 public native void setVideoSource(int video_source) 231 throws IllegalStateException; 232 233 /** 234 * Sets the format of the output file produced during recording. Call this 235 * after setAudioSource()/setVideoSource() but before prepare(). 236 * 237 * <p>It is recommended to always use 3GP format when using the H.263 238 * video encoder and AMR audio encoder. Using an MPEG-4 container format 239 * may confuse some desktop players.</p> 240 * 241 * @param output_format the output format to use. The output format 242 * needs to be specified before setting recording-parameters or encoders. 243 * @throws IllegalStateException if it is called after prepare() or before 244 * setAudioSource()/setVideoSource(). 245 * @see android.media.MediaRecorder.OutputFormat 246 */ 247 public native void setOutputFormat(int output_format) 248 throws IllegalStateException; 249 250 /** 251 * Sets the width and height of the video to be captured. Must be called 252 * after setVideoSource(). Call this after setOutFormat() but before 253 * prepare(). 254 * 255 * @param width the width of the video to be captured 256 * @param height the height of the video to be captured 257 * @throws IllegalStateException if it is called after 258 * prepare() or before setOutputFormat() 259 */ 260 public native void setVideoSize(int width, int height) 261 throws IllegalStateException; 262 263 /** 264 * Sets the frame rate of the video to be captured. Must be called 265 * after setVideoSource(). Call this after setOutFormat() but before 266 * prepare(). 267 * 268 * @param rate the number of frames per second of video to capture 269 * @throws IllegalStateException if it is called after 270 * prepare() or before setOutputFormat(). 271 * 272 * NOTE: On some devices that have auto-frame rate, this sets the 273 * maximum frame rate, not a constant frame rate. Actual frame rate 274 * will vary according to lighting conditions. 275 */ 276 public native void setVideoFrameRate(int rate) throws IllegalStateException; 277 278 /** 279 * Sets the maximum duration (in ms) of the recording session. 280 * Call this after setOutFormat() but before prepare(). 281 * After recording reaches the specified duration, a notification 282 * will be sent to the {@link android.media.MediaRecorder.OnInfoListener} 283 * with a "what" code of {@link #MEDIA_RECORDER_INFO_MAX_DURATION_REACHED} 284 * and recording will be stopped. Stopping happens asynchronously, there 285 * is no guarantee that the recorder will have stopped by the time the 286 * listener is notified. 287 * 288 * @param max_duration_ms the maximum duration in ms (if zero or negative, disables the duration limit) 289 * 290 */ 291 public native void setMaxDuration(int max_duration_ms) throws IllegalArgumentException; 292 293 /** 294 * Sets the maximum filesize (in bytes) of the recording session. 295 * Call this after setOutFormat() but before prepare(). 296 * After recording reaches the specified filesize, a notification 297 * will be sent to the {@link android.media.MediaRecorder.OnInfoListener} 298 * with a "what" code of {@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED} 299 * and recording will be stopped. Stopping happens asynchronously, there 300 * is no guarantee that the recorder will have stopped by the time the 301 * listener is notified. 302 * 303 * @param max_filesize_bytes the maximum filesize in bytes (if zero or negative, disables the limit) 304 * 305 */ 306 public native void setMaxFileSize(long max_filesize_bytes) throws IllegalArgumentException; 307 308 /** 309 * Sets the audio encoder to be used for recording. If this method is not 310 * called, the output file will not contain an audio track. Call this after 311 * setOutputFormat() but before prepare(). 312 * 313 * @param audio_encoder the audio encoder to use. 314 * @throws IllegalStateException if it is called before 315 * setOutputFormat() or after prepare(). 316 * @see android.media.MediaRecorder.AudioEncoder 317 */ 318 public native void setAudioEncoder(int audio_encoder) 319 throws IllegalStateException; 320 321 /** 322 * Sets the video encoder to be used for recording. If this method is not 323 * called, the output file will not contain an video track. Call this after 324 * setOutputFormat() and before prepare(). 325 * 326 * @param video_encoder the video encoder to use. 327 * @throws IllegalStateException if it is called before 328 * setOutputFormat() or after prepare() 329 * @see android.media.MediaRecorder.VideoEncoder 330 */ 331 public native void setVideoEncoder(int video_encoder) 332 throws IllegalStateException; 333 334 /** 335 * Pass in the file descriptor of the file to be written. Call this after 336 * setOutputFormat() but before prepare(). 337 * 338 * @param fd an open file descriptor to be written into. 339 * @throws IllegalStateException if it is called before 340 * setOutputFormat() or after prepare() 341 */ 342 public void setOutputFile(FileDescriptor fd) throws IllegalStateException 343 { 344 mPath = null; 345 mFd = fd; 346 } 347 348 /** 349 * Sets the path of the output file to be produced. Call this after 350 * setOutputFormat() but before prepare(). 351 * 352 * @param path The pathname to use. 353 * @throws IllegalStateException if it is called before 354 * setOutputFormat() or after prepare() 355 */ 356 public void setOutputFile(String path) throws IllegalStateException 357 { 358 mFd = null; 359 mPath = path; 360 } 361 362 // native implementation 363 private native void _setOutputFile(FileDescriptor fd, long offset, long length) 364 throws IllegalStateException, IOException; 365 private native void _prepare() throws IllegalStateException, IOException; 366 367 /** 368 * Prepares the recorder to begin capturing and encoding data. This method 369 * must be called after setting up the desired audio and video sources, 370 * encoders, file format, etc., but before start(). 371 * 372 * @throws IllegalStateException if it is called after 373 * start() or before setOutputFormat(). 374 * @throws IOException if prepare fails otherwise. 375 */ 376 public void prepare() throws IllegalStateException, IOException 377 { 378 if (mPath != null) { 379 FileOutputStream fos = new FileOutputStream(mPath); 380 try { 381 _setOutputFile(fos.getFD(), 0, 0); 382 } finally { 383 fos.close(); 384 } 385 } else if (mFd != null) { 386 _setOutputFile(mFd, 0, 0); 387 } else { 388 throw new IOException("No valid output file"); 389 } 390 _prepare(); 391 } 392 393 /** 394 * Begins capturing and encoding data to the file specified with 395 * setOutputFile(). Call this after prepare(). 396 * 397 * @throws IllegalStateException if it is called before 398 * prepare(). 399 */ 400 public native void start() throws IllegalStateException; 401 402 /** 403 * Stops recording. Call this after start(). Once recording is stopped, 404 * you will have to configure it again as if it has just been constructed. 405 * 406 * @throws IllegalStateException if it is called before start() 407 */ 408 public native void stop() throws IllegalStateException; 409 410 /** 411 * Restarts the MediaRecorder to its idle state. After calling 412 * this method, you will have to configure it again as if it had just been 413 * constructed. 414 */ 415 public void reset() { 416 native_reset(); 417 418 // make sure none of the listeners get called anymore 419 mEventHandler.removeCallbacksAndMessages(null); 420 } 421 422 private native void native_reset(); 423 424 /** 425 * Returns the maximum absolute amplitude that was sampled since the last 426 * call to this method. Call this only after the setAudioSource(). 427 * 428 * @return the maximum absolute amplitude measured since the last call, or 429 * 0 when called for the first time 430 * @throws IllegalStateException if it is called before 431 * the audio source has been set. 432 */ 433 public native int getMaxAmplitude() throws IllegalStateException; 434 435 /* Do not change this value without updating its counterpart 436 * in include/media/mediarecorder.h! 437 */ 438 /** Unspecified media recorder error. 439 * @see android.media.MediaRecorder.OnErrorListener 440 */ 441 public static final int MEDIA_RECORDER_ERROR_UNKNOWN = 1; 442 443 /** 444 * Interface definition for a callback to be invoked when an error 445 * occurs while recording. 446 */ 447 public interface OnErrorListener 448 { 449 /** 450 * Called when an error occurs while recording. 451 * 452 * @param mr the MediaRecorder that encountered the error 453 * @param what the type of error that has occurred: 454 * <ul> 455 * <li>{@link #MEDIA_RECORDER_ERROR_UNKNOWN} 456 * </ul> 457 * @param extra an extra code, specific to the error type 458 */ 459 void onError(MediaRecorder mr, int what, int extra); 460 } 461 462 /** 463 * Register a callback to be invoked when an error occurs while 464 * recording. 465 * 466 * @param l the callback that will be run 467 */ 468 public void setOnErrorListener(OnErrorListener l) 469 { 470 mOnErrorListener = l; 471 } 472 473 /* Do not change these values without updating their counterparts 474 * in include/media/mediarecorder.h! 475 */ 476 /** Unspecified media recorder error. 477 * @see android.media.MediaRecorder.OnInfoListener 478 */ 479 public static final int MEDIA_RECORDER_INFO_UNKNOWN = 1; 480 /** A maximum duration had been setup and has now been reached. 481 * @see android.media.MediaRecorder.OnInfoListener 482 */ 483 public static final int MEDIA_RECORDER_INFO_MAX_DURATION_REACHED = 800; 484 /** A maximum filesize had been setup and has now been reached. 485 * @see android.media.MediaRecorder.OnInfoListener 486 */ 487 public static final int MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED = 801; 488 489 /** 490 * Interface definition for a callback to be invoked when an error 491 * occurs while recording. 492 */ 493 public interface OnInfoListener 494 { 495 /** 496 * Called when an error occurs while recording. 497 * 498 * @param mr the MediaRecorder that encountered the error 499 * @param what the type of error that has occurred: 500 * <ul> 501 * <li>{@link #MEDIA_RECORDER_INFO_UNKNOWN} 502 * <li>{@link #MEDIA_RECORDER_INFO_MAX_DURATION_REACHED} 503 * <li>{@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED} 504 * </ul> 505 * @param extra an extra code, specific to the error type 506 */ 507 void onInfo(MediaRecorder mr, int what, int extra); 508 } 509 510 /** 511 * Register a callback to be invoked when an informational event occurs while 512 * recording. 513 * 514 * @param listener the callback that will be run 515 */ 516 public void setOnInfoListener(OnInfoListener listener) 517 { 518 mOnInfoListener = listener; 519 } 520 521 private class EventHandler extends Handler 522 { 523 private MediaRecorder mMediaRecorder; 524 525 public EventHandler(MediaRecorder mr, Looper looper) { 526 super(looper); 527 mMediaRecorder = mr; 528 } 529 530 /* Do not change these values without updating their counterparts 531 * in include/media/mediarecorder.h! 532 */ 533 private static final int MEDIA_RECORDER_EVENT_ERROR = 1; 534 private static final int MEDIA_RECORDER_EVENT_INFO = 2; 535 536 @Override 537 public void handleMessage(Message msg) { 538 if (mMediaRecorder.mNativeContext == 0) { 539 Log.w(TAG, "mediarecorder went away with unhandled events"); 540 return; 541 } 542 switch(msg.what) { 543 case MEDIA_RECORDER_EVENT_ERROR: 544 if (mOnErrorListener != null) 545 mOnErrorListener.onError(mMediaRecorder, msg.arg1, msg.arg2); 546 547 return; 548 549 case MEDIA_RECORDER_EVENT_INFO: 550 if (mOnInfoListener != null) 551 mOnInfoListener.onInfo(mMediaRecorder, msg.arg1, msg.arg2); 552 553 return; 554 555 default: 556 Log.e(TAG, "Unknown message type " + msg.what); 557 return; 558 } 559 } 560 } 561 562 /** 563 * Called from native code when an interesting event happens. This method 564 * just uses the EventHandler system to post the event back to the main app thread. 565 * We use a weak reference to the original MediaRecorder object so that the native 566 * code is safe from the object disappearing from underneath it. (This is 567 * the cookie passed to native_setup().) 568 */ 569 private static void postEventFromNative(Object mediarecorder_ref, 570 int what, int arg1, int arg2, Object obj) 571 { 572 MediaRecorder mr = (MediaRecorder)((WeakReference)mediarecorder_ref).get(); 573 if (mr == null) { 574 return; 575 } 576 577 if (mr.mEventHandler != null) { 578 Message m = mr.mEventHandler.obtainMessage(what, arg1, arg2, obj); 579 mr.mEventHandler.sendMessage(m); 580 } 581 } 582 583 /** 584 * Releases resources associated with this MediaRecorder object. 585 * It is good practice to call this method when you're done 586 * using the MediaRecorder. 587 */ 588 public native void release(); 589 590 private native final void native_setup(Object mediarecorder_this) throws IllegalStateException; 591 592 private native final void native_finalize(); 593 594 @Override 595 protected void finalize() { native_finalize(); } 596} 597