MediaRecorder.java revision ba87e3e6c985e7175152993b5efcc7dd2f0e1c93
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 * 263 * @param max_duration_ms the maximum duration in ms (if zero or negative, disables the duration limit) 264 * 265 */ 266 public native void setMaxDuration(int max_duration_ms) throws IllegalArgumentException; 267 268 /** 269 * Sets the audio encoder to be used for recording. If this method is not 270 * called, the output file will not contain an audio track. Call this after 271 * setOutputFormat() but before prepare(). 272 * 273 * @param audio_encoder the audio encoder to use. 274 * @throws IllegalStateException if it is called before 275 * setOutputFormat() or after prepare(). 276 * @see android.media.MediaRecorder.AudioEncoder 277 */ 278 public native void setAudioEncoder(int audio_encoder) 279 throws IllegalStateException; 280 281 /** 282 * Sets the video encoder to be used for recording. If this method is not 283 * called, the output file will not contain an video track. Call this after 284 * setOutputFormat() and before prepare(). 285 * 286 * @param video_encoder the video encoder to use. 287 * @throws IllegalStateException if it is called before 288 * setOutputFormat() or after prepare() 289 * @see android.media.MediaRecorder.VideoEncoder 290 */ 291 public native void setVideoEncoder(int video_encoder) 292 throws IllegalStateException; 293 294 /** 295 * Pass in the file descriptor of the file to be written. Call this after 296 * setOutputFormat() but before prepare(). 297 * 298 * @param fd an open file descriptor to be written into. 299 * @throws IllegalStateException if it is called before 300 * setOutputFormat() or after prepare() 301 */ 302 public void setOutputFile(FileDescriptor fd) throws IllegalStateException 303 { 304 mPath = null; 305 mFd = fd; 306 } 307 308 /** 309 * Sets the path of the output file to be produced. Call this after 310 * setOutputFormat() but before prepare(). 311 * 312 * @param path The pathname to use. 313 * @throws IllegalStateException if it is called before 314 * setOutputFormat() or after prepare() 315 */ 316 public void setOutputFile(String path) throws IllegalStateException 317 { 318 mFd = null; 319 mPath = path; 320 } 321 322 // native implementation 323 private native void _setOutputFile(FileDescriptor fd, long offset, long length) 324 throws IllegalStateException, IOException; 325 private native void _prepare() throws IllegalStateException, IOException; 326 327 /** 328 * Prepares the recorder to begin capturing and encoding data. This method 329 * must be called after setting up the desired audio and video sources, 330 * encoders, file format, etc., but before start(). 331 * 332 * @throws IllegalStateException if it is called after 333 * start() or before setOutputFormat(). 334 * @throws IOException if prepare fails otherwise. 335 */ 336 public void prepare() throws IllegalStateException, IOException 337 { 338 if (mPath != null) { 339 FileOutputStream fos = new FileOutputStream(mPath); 340 try { 341 _setOutputFile(fos.getFD(), 0, 0); 342 } finally { 343 fos.close(); 344 } 345 } else if (mFd != null) { 346 _setOutputFile(mFd, 0, 0); 347 } else { 348 throw new IOException("No valid output file"); 349 } 350 _prepare(); 351 } 352 353 /** 354 * Begins capturing and encoding data to the file specified with 355 * setOutputFile(). Call this after prepare(). 356 * 357 * @throws IllegalStateException if it is called before 358 * prepare(). 359 */ 360 public native void start() throws IllegalStateException; 361 362 /** 363 * Stops recording. Call this after start(). Once recording is stopped, 364 * you will have to configure it again as if it has just been constructed. 365 * 366 * @throws IllegalStateException if it is called before start() 367 */ 368 public native void stop() throws IllegalStateException; 369 370 /** 371 * Restarts the MediaRecorder to its idle state. After calling 372 * this method, you will have to configure it again as if it had just been 373 * constructed. 374 */ 375 public void reset() { 376 native_reset(); 377 378 // make sure none of the listeners get called anymore 379 mEventHandler.removeCallbacksAndMessages(null); 380 } 381 382 private native void native_reset(); 383 384 /** 385 * Returns the maximum absolute amplitude that was sampled since the last 386 * call to this method. Call this only after the setAudioSource(). 387 * 388 * @return the maximum absolute amplitude measured since the last call, or 389 * 0 when called for the first time 390 * @throws IllegalStateException if it is called before 391 * the audio source has been set. 392 */ 393 public native int getMaxAmplitude() throws IllegalStateException; 394 395 /* Do not change this value without updating its counterpart 396 * in include/media/mediarecorder.h! 397 */ 398 /** Unspecified media recorder error. 399 * @see android.media.MediaRecorder.OnErrorListener 400 */ 401 public static final int MEDIA_RECORDER_ERROR_UNKNOWN = 1; 402 403 /** 404 * Interface definition for a callback to be invoked when an error 405 * occurs while recording. 406 */ 407 public interface OnErrorListener 408 { 409 /** 410 * Called when an error occurs while recording. 411 * 412 * @param mr the MediaRecorder that encountered the error 413 * @param what the type of error that has occurred: 414 * <ul> 415 * <li>{@link #MEDIA_RECORDER_ERROR_UNKNOWN} 416 * </ul> 417 * @param extra an extra code, specific to the error type 418 */ 419 void onError(MediaRecorder mr, int what, int extra); 420 } 421 422 /** 423 * Register a callback to be invoked when an error occurs while 424 * recording. 425 * 426 * @param l the callback that will be run 427 */ 428 public void setOnErrorListener(OnErrorListener l) 429 { 430 mOnErrorListener = l; 431 } 432 433 /* Do not change these values without updating their counterparts 434 * in include/media/mediarecorder.h! 435 */ 436 /** Unspecified media recorder error. 437 * @see android.media.MediaRecorder.OnInfoListener 438 */ 439 public static final int MEDIA_RECORDER_INFO_UNKNOWN = 1; 440 /** A maximum duration had been setup and has now been reached. 441 * @see android.media.MediaRecorder.OnInfoListener 442 */ 443 public static final int MEDIA_RECORDER_INFO_MAX_DURATION_REACHED = 800; 444 445 /** 446 * Interface definition for a callback to be invoked when an error 447 * occurs while recording. 448 */ 449 public interface OnInfoListener 450 { 451 /** 452 * Called when an error occurs while recording. 453 * 454 * @param mr the MediaRecorder that encountered the error 455 * @param what the type of error that has occurred: 456 * <ul> 457 * <li>{@link #MEDIA_RECORDER_INFO_UNKNOWN} 458 * </ul> 459 * @param extra an extra code, specific to the error type 460 */ 461 void onInfo(MediaRecorder mr, int what, int extra); 462 } 463 464 /** 465 * Register a callback to be invoked when an informational event occurs while 466 * recording. 467 * 468 * @param listener the callback that will be run 469 */ 470 public void setOnInfoListener(OnInfoListener listener) 471 { 472 mOnInfoListener = listener; 473 } 474 475 private class EventHandler extends Handler 476 { 477 private MediaRecorder mMediaRecorder; 478 479 public EventHandler(MediaRecorder mr, Looper looper) { 480 super(looper); 481 mMediaRecorder = mr; 482 } 483 484 /* Do not change these values without updating their counterparts 485 * in include/media/mediarecorder.h! 486 */ 487 private static final int MEDIA_RECORDER_EVENT_ERROR = 1; 488 private static final int MEDIA_RECORDER_EVENT_INFO = 2; 489 490 @Override 491 public void handleMessage(Message msg) { 492 if (mMediaRecorder.mNativeContext == 0) { 493 Log.w(TAG, "mediarecorder went away with unhandled events"); 494 return; 495 } 496 switch(msg.what) { 497 case MEDIA_RECORDER_EVENT_ERROR: 498 if (mOnErrorListener != null) 499 mOnErrorListener.onError(mMediaRecorder, msg.arg1, msg.arg2); 500 501 return; 502 503 case MEDIA_RECORDER_EVENT_INFO: 504 if (mOnInfoListener != null) 505 mOnInfoListener.onInfo(mMediaRecorder, msg.arg1, msg.arg2); 506 507 return; 508 509 default: 510 Log.e(TAG, "Unknown message type " + msg.what); 511 return; 512 } 513 } 514 } 515 516 /** 517 * Called from native code when an interesting event happens. This method 518 * just uses the EventHandler system to post the event back to the main app thread. 519 * We use a weak reference to the original MediaRecorder object so that the native 520 * code is safe from the object disappearing from underneath it. (This is 521 * the cookie passed to native_setup().) 522 */ 523 private static void postEventFromNative(Object mediarecorder_ref, 524 int what, int arg1, int arg2, Object obj) 525 { 526 MediaRecorder mr = (MediaRecorder)((WeakReference)mediarecorder_ref).get(); 527 if (mr == null) { 528 return; 529 } 530 531 if (mr.mEventHandler != null) { 532 Message m = mr.mEventHandler.obtainMessage(what, arg1, arg2, obj); 533 mr.mEventHandler.sendMessage(m); 534 } 535 } 536 537 /** 538 * Releases resources associated with this MediaRecorder object. 539 * It is good practice to call this method when you're done 540 * using the MediaRecorder. 541 */ 542 public native void release(); 543 544 private native final void native_setup(Object mediarecorder_this) throws IllegalStateException; 545 546 private native final void native_finalize(); 547 548 @Override 549 protected void finalize() { native_finalize(); } 550} 551