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