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 17 package android.media; 18 19 import android.annotation.CallbackExecutor; 20 import android.annotation.FloatRange; 21 import android.annotation.IntDef; 22 import android.annotation.NonNull; 23 import android.annotation.Nullable; 24 import android.annotation.RequiresPermission; 25 import android.annotation.SystemApi; 26 import android.app.ActivityThread; 27 import android.compat.annotation.UnsupportedAppUsage; 28 import android.content.AttributionSource; 29 import android.content.AttributionSource.ScopedParcelState; 30 import android.content.Context; 31 import android.hardware.Camera; 32 import android.media.metrics.LogSessionId; 33 import android.os.Build; 34 import android.os.Handler; 35 import android.os.Looper; 36 import android.os.Message; 37 import android.os.Parcel; 38 import android.os.PersistableBundle; 39 import android.util.ArrayMap; 40 import android.util.Log; 41 import android.util.Pair; 42 import android.view.Surface; 43 44 import com.android.internal.annotations.GuardedBy; 45 import com.android.internal.util.Preconditions; 46 47 import java.io.File; 48 import java.io.FileDescriptor; 49 import java.io.IOException; 50 import java.io.RandomAccessFile; 51 import java.lang.annotation.Retention; 52 import java.lang.annotation.RetentionPolicy; 53 import java.lang.ref.WeakReference; 54 import java.util.ArrayList; 55 import java.util.List; 56 import java.util.Objects; 57 import java.util.concurrent.Executor; 58 59 /** 60 * Used to record audio and video. The recording control is based on a 61 * simple state machine (see below). 62 * 63 * <p><img src="{@docRoot}images/mediarecorder_state_diagram.gif" border="0" /> 64 * </p> 65 * 66 * <p>A common case of using MediaRecorder to record audio works as follows: 67 * 68 * <pre> 69 * MediaRecorder recorder = new MediaRecorder(context); 70 * recorder.setAudioSource(MediaRecorder.AudioSource.MIC); 71 * recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); 72 * recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); 73 * recorder.setOutputFile(PATH_NAME); 74 * recorder.prepare(); 75 * recorder.start(); // Recording is now started 76 * ... 77 * recorder.stop(); 78 * recorder.reset(); // You can reuse the object by going back to setAudioSource() step 79 * recorder.release(); // Now the object cannot be reused 80 * </pre> 81 * 82 * <p>Applications may want to register for informational and error 83 * events in order to be informed of some internal update and possible 84 * runtime errors during recording. Registration for such events is 85 * done by setting the appropriate listeners (via calls 86 * (to {@link #setOnInfoListener(OnInfoListener)}setOnInfoListener and/or 87 * {@link #setOnErrorListener(OnErrorListener)}setOnErrorListener). 88 * In order to receive the respective callback associated with these listeners, 89 * applications are required to create MediaRecorder objects on threads with a 90 * Looper running (the main UI thread by default already has a Looper running). 91 * 92 * <p><strong>Note:</strong> Currently, MediaRecorder does not work on the emulator. 93 * 94 * <div class="special reference"> 95 * <h3>Developer Guides</h3> 96 * <p>For more information about how to use MediaRecorder for recording video, read the 97 * <a href="{@docRoot}guide/topics/media/camera.html#capture-video">Camera</a> developer guide. 98 * For more information about how to use MediaRecorder for recording sound, read the 99 * <a href="{@docRoot}guide/topics/media/audio-capture.html">Audio Capture</a> developer guide.</p> 100 * </div> 101 */ 102 public class MediaRecorder implements AudioRouting, 103 AudioRecordingMonitor, 104 AudioRecordingMonitorClient, 105 MicrophoneDirection 106 { 107 static { 108 System.loadLibrary("media_jni"); native_init()109 native_init(); 110 } 111 private final static String TAG = "MediaRecorder"; 112 113 // The two fields below are accessed by native methods 114 @SuppressWarnings("unused") 115 private long mNativeContext; 116 117 @SuppressWarnings("unused") 118 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 119 private Surface mSurface; 120 121 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) 122 private String mPath; 123 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) 124 private FileDescriptor mFd; 125 private File mFile; 126 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) 127 private EventHandler mEventHandler; 128 @UnsupportedAppUsage 129 private OnErrorListener mOnErrorListener; 130 @UnsupportedAppUsage 131 private OnInfoListener mOnInfoListener; 132 133 private int mChannelCount; 134 135 @NonNull private LogSessionId mLogSessionId = LogSessionId.LOG_SESSION_ID_NONE; 136 137 /** 138 * Default constructor. 139 * 140 * @deprecated Use {@link #MediaRecorder(Context)} instead 141 */ 142 @Deprecated MediaRecorder()143 public MediaRecorder() { 144 this(ActivityThread.currentApplication()); 145 } 146 147 /** 148 * Default constructor. 149 * 150 * @param context Context the recorder belongs to 151 */ MediaRecorder(@onNull Context context)152 public MediaRecorder(@NonNull Context context) { 153 Objects.requireNonNull(context); 154 Looper looper; 155 if ((looper = Looper.myLooper()) != null) { 156 mEventHandler = new EventHandler(this, looper); 157 } else if ((looper = Looper.getMainLooper()) != null) { 158 mEventHandler = new EventHandler(this, looper); 159 } else { 160 mEventHandler = null; 161 } 162 163 mChannelCount = 1; 164 /* Native setup requires a weak reference to our object. 165 * It's easier to create it here than in C++. 166 */ 167 try (ScopedParcelState attributionSourceState = context.getAttributionSource() 168 .asScopedParcelState()) { 169 native_setup(new WeakReference<>(this), ActivityThread.currentPackageName(), 170 attributionSourceState.getParcel()); 171 } 172 } 173 174 /** 175 * 176 * Sets the {@link LogSessionId} for MediaRecorder. 177 * 178 * <p>The log session ID is a random 32-byte hexadecimal string that is used for monitoring the 179 * MediaRecorder performance.</p> 180 * 181 * @param id the global ID for monitoring the MediaRecorder performance 182 */ setLogSessionId(@onNull LogSessionId id)183 public void setLogSessionId(@NonNull LogSessionId id) { 184 Objects.requireNonNull(id); 185 mLogSessionId = id; 186 setParameter("log-session-id=" + id.getStringId()); 187 } 188 189 /** 190 * Returns the {@link LogSessionId} for MediaRecorder. 191 * 192 * @return the global ID for monitoring the MediaRecorder performance 193 */ 194 @NonNull getLogSessionId()195 public LogSessionId getLogSessionId() { 196 return mLogSessionId; 197 } 198 199 /** 200 * Sets a {@link android.hardware.Camera} to use for recording. 201 * 202 * <p>Use this function to switch quickly between preview and capture mode without a teardown of 203 * the camera object. {@link android.hardware.Camera#unlock()} should be called before 204 * this. Must call before {@link #prepare}.</p> 205 * 206 * @param c the Camera to use for recording 207 * @deprecated Use {@link #getSurface} and the {@link android.hardware.camera2} API instead. 208 */ 209 @Deprecated setCamera(Camera c)210 public native void setCamera(Camera c); 211 212 /** 213 * Gets the surface to record from when using SURFACE video source. 214 * 215 * <p> May only be called after {@link #prepare}. Frames rendered to the Surface before 216 * {@link #start} will be discarded.</p> 217 * 218 * @throws IllegalStateException if it is called before {@link #prepare}, after 219 * {@link #stop}, or is called when VideoSource is not set to SURFACE. 220 * @see android.media.MediaRecorder.VideoSource 221 */ getSurface()222 public native Surface getSurface(); 223 224 /** 225 * Configures the recorder to use a persistent surface when using SURFACE video source. 226 * <p> May only be called before {@link #prepare}. If called, {@link #getSurface} should 227 * not be used and will throw IllegalStateException. Frames rendered to the Surface 228 * before {@link #start} will be discarded.</p> 229 230 * @param surface a persistent input surface created by 231 * {@link MediaCodec#createPersistentInputSurface} 232 * @throws IllegalStateException if it is called after {@link #prepare} and before 233 * {@link #stop}. 234 * @throws IllegalArgumentException if the surface was not created by 235 * {@link MediaCodec#createPersistentInputSurface}. 236 * @see MediaCodec#createPersistentInputSurface 237 * @see MediaRecorder.VideoSource 238 */ setInputSurface(@onNull Surface surface)239 public void setInputSurface(@NonNull Surface surface) { 240 if (!(surface instanceof MediaCodec.PersistentSurface)) { 241 throw new IllegalArgumentException("not a PersistentSurface"); 242 } 243 native_setInputSurface(surface); 244 } 245 native_setInputSurface(@onNull Surface surface)246 private native final void native_setInputSurface(@NonNull Surface surface); 247 248 /** 249 * Sets a Surface to show a preview of recorded media (video). Calls this 250 * before prepare() to make sure that the desirable preview display is 251 * set. If {@link #setCamera(Camera)} is used and the surface has been 252 * already set to the camera, application do not need to call this. If 253 * this is called with non-null surface, the preview surface of the camera 254 * will be replaced by the new surface. If this method is called with null 255 * surface or not called at all, media recorder will not change the preview 256 * surface of the camera. 257 * 258 * @param sv the Surface to use for the preview 259 * @see android.hardware.Camera#setPreviewDisplay(android.view.SurfaceHolder) 260 */ setPreviewDisplay(Surface sv)261 public void setPreviewDisplay(Surface sv) { 262 mSurface = sv; 263 } 264 265 /** 266 * Defines the audio source. 267 * An audio source defines both a default physical source of audio signal, and a recording 268 * configuration. These constants are for instance used 269 * in {@link MediaRecorder#setAudioSource(int)} or 270 * {@link AudioRecord.Builder#setAudioSource(int)}. 271 */ 272 public final class AudioSource { 273 AudioSource()274 private AudioSource() {} 275 276 /** @hide */ 277 public final static int AUDIO_SOURCE_INVALID = -1; 278 279 /* Do not change these values without updating their counterparts 280 * in system/media/audio/include/system/audio.h! 281 */ 282 283 /** Default audio source **/ 284 public static final int DEFAULT = 0; 285 286 /** Microphone audio source */ 287 public static final int MIC = 1; 288 289 /** Voice call uplink (Tx) audio source. 290 * <p> 291 * Capturing from <code>VOICE_UPLINK</code> source requires the 292 * {@link android.Manifest.permission#CAPTURE_AUDIO_OUTPUT} permission. 293 * This permission is reserved for use by system components and is not available to 294 * third-party applications. 295 * </p> 296 */ 297 public static final int VOICE_UPLINK = 2; 298 299 /** Voice call downlink (Rx) audio source. 300 * <p> 301 * Capturing from <code>VOICE_DOWNLINK</code> source requires the 302 * {@link android.Manifest.permission#CAPTURE_AUDIO_OUTPUT} permission. 303 * This permission is reserved for use by system components and is not available to 304 * third-party applications. 305 * </p> 306 */ 307 public static final int VOICE_DOWNLINK = 3; 308 309 /** Voice call uplink + downlink audio source 310 * <p> 311 * Capturing from <code>VOICE_CALL</code> source requires the 312 * {@link android.Manifest.permission#CAPTURE_AUDIO_OUTPUT} permission. 313 * This permission is reserved for use by system components and is not available to 314 * third-party applications. 315 * </p> 316 */ 317 public static final int VOICE_CALL = 4; 318 319 /** Microphone audio source tuned for video recording, with the same orientation 320 * as the camera if available. */ 321 public static final int CAMCORDER = 5; 322 323 /** Microphone audio source tuned for voice recognition. */ 324 public static final int VOICE_RECOGNITION = 6; 325 326 /** Microphone audio source tuned for voice communications such as VoIP. It 327 * will for instance take advantage of echo cancellation or automatic gain control 328 * if available. 329 */ 330 public static final int VOICE_COMMUNICATION = 7; 331 332 /** 333 * Audio source for a submix of audio streams to be presented remotely. 334 * <p> 335 * An application can use this audio source to capture a mix of audio streams 336 * that should be transmitted to a remote receiver such as a Wifi display. 337 * While recording is active, these audio streams are redirected to the remote 338 * submix instead of being played on the device speaker or headset. 339 * </p><p> 340 * Certain streams are excluded from the remote submix, including 341 * {@link AudioManager#STREAM_RING}, {@link AudioManager#STREAM_ALARM}, 342 * and {@link AudioManager#STREAM_NOTIFICATION}. These streams will continue 343 * to be presented locally as usual. 344 * </p><p> 345 * Capturing the remote submix audio requires the 346 * {@link android.Manifest.permission#CAPTURE_AUDIO_OUTPUT} permission. 347 * This permission is reserved for use by system components and is not available to 348 * third-party applications. 349 * </p> 350 */ 351 @RequiresPermission(android.Manifest.permission.CAPTURE_AUDIO_OUTPUT) 352 public static final int REMOTE_SUBMIX = 8; 353 354 /** Microphone audio source tuned for unprocessed (raw) sound if available, behaves like 355 * {@link #DEFAULT} otherwise. */ 356 public static final int UNPROCESSED = 9; 357 358 359 /** 360 * Source for capturing audio meant to be processed in real time and played back for live 361 * performance (e.g karaoke). 362 * <p> 363 * The capture path will minimize latency and coupling with 364 * playback path. 365 * </p> 366 */ 367 public static final int VOICE_PERFORMANCE = 10; 368 369 370 /** 371 * Source for an echo canceller to capture the reference signal to be cancelled. 372 * <p> 373 * The echo reference signal will be captured as close as possible to the DAC in order 374 * to include all post processing applied to the playback path. 375 * </p><p> 376 * Capturing the echo reference requires the 377 * {@link android.Manifest.permission#CAPTURE_AUDIO_OUTPUT} permission. 378 * This permission is reserved for use by system components and is not available to 379 * third-party applications. 380 * </p> 381 * @hide 382 */ 383 @SystemApi 384 @RequiresPermission(android.Manifest.permission.CAPTURE_AUDIO_OUTPUT) 385 public static final int ECHO_REFERENCE = 1997; 386 387 /** 388 * Audio source for capturing broadcast radio tuner output. 389 * Capturing the radio tuner output requires the 390 * {@link android.Manifest.permission#CAPTURE_AUDIO_OUTPUT} permission. 391 * This permission is reserved for use by system components and is not available to 392 * third-party applications. 393 * @hide 394 */ 395 @SystemApi 396 @RequiresPermission(android.Manifest.permission.CAPTURE_AUDIO_OUTPUT) 397 public static final int RADIO_TUNER = 1998; 398 399 /** 400 * Audio source for preemptible, low-priority software hotword detection 401 * It presents the same gain and pre-processing tuning as {@link #VOICE_RECOGNITION}. 402 * <p> 403 * An application should use this audio source when it wishes to do 404 * always-on software hotword detection, while gracefully giving in to any other application 405 * that might want to read from the microphone. 406 * </p> 407 * This is a hidden audio source. 408 * @hide 409 */ 410 @SystemApi 411 @RequiresPermission(android.Manifest.permission.CAPTURE_AUDIO_HOTWORD) 412 public static final int HOTWORD = 1999; 413 414 /** Microphone audio source for ultrasound sound if available, behaves like 415 * {@link #DEFAULT} otherwise. 416 * @hide 417 */ 418 @SystemApi 419 @RequiresPermission(android.Manifest.permission.ACCESS_ULTRASOUND) 420 public static final int ULTRASOUND = 2000; 421 422 } 423 424 /** @hide */ 425 @IntDef({ 426 AudioSource.DEFAULT, 427 AudioSource.MIC, 428 AudioSource.VOICE_UPLINK, 429 AudioSource.VOICE_DOWNLINK, 430 AudioSource.VOICE_CALL, 431 AudioSource.CAMCORDER, 432 AudioSource.VOICE_RECOGNITION, 433 AudioSource.VOICE_COMMUNICATION, 434 AudioSource.UNPROCESSED, 435 AudioSource.VOICE_PERFORMANCE, 436 }) 437 @Retention(RetentionPolicy.SOURCE) 438 public @interface Source {} 439 440 /** @hide */ 441 @IntDef({ 442 AudioSource.DEFAULT, 443 AudioSource.MIC, 444 AudioSource.VOICE_UPLINK, 445 AudioSource.VOICE_DOWNLINK, 446 AudioSource.VOICE_CALL, 447 AudioSource.CAMCORDER, 448 AudioSource.VOICE_RECOGNITION, 449 AudioSource.VOICE_COMMUNICATION, 450 AudioSource.REMOTE_SUBMIX, 451 AudioSource.UNPROCESSED, 452 AudioSource.VOICE_PERFORMANCE, 453 AudioSource.ECHO_REFERENCE, 454 AudioSource.RADIO_TUNER, 455 AudioSource.HOTWORD, 456 AudioSource.ULTRASOUND, 457 }) 458 @Retention(RetentionPolicy.SOURCE) 459 public @interface SystemSource {} 460 461 // TODO make AudioSource static (API change) and move this method inside the AudioSource class 462 /** 463 * @hide 464 * @param source An audio source to test 465 * @return true if the source is only visible to system components 466 */ isSystemOnlyAudioSource(int source)467 public static boolean isSystemOnlyAudioSource(int source) { 468 switch(source) { 469 case AudioSource.DEFAULT: 470 case AudioSource.MIC: 471 case AudioSource.VOICE_UPLINK: 472 case AudioSource.VOICE_DOWNLINK: 473 case AudioSource.VOICE_CALL: 474 case AudioSource.CAMCORDER: 475 case AudioSource.VOICE_RECOGNITION: 476 case AudioSource.VOICE_COMMUNICATION: 477 //case REMOTE_SUBMIX: considered "system" as it requires system permissions 478 case AudioSource.UNPROCESSED: 479 case AudioSource.VOICE_PERFORMANCE: 480 return false; 481 default: 482 return true; 483 } 484 } 485 486 /** 487 * @hide 488 * @param source An audio source to test 489 * @return true if the source is a valid one 490 */ isValidAudioSource(int source)491 public static boolean isValidAudioSource(int source) { 492 switch(source) { 493 case AudioSource.MIC: 494 case AudioSource.VOICE_UPLINK: 495 case AudioSource.VOICE_DOWNLINK: 496 case AudioSource.VOICE_CALL: 497 case AudioSource.CAMCORDER: 498 case AudioSource.VOICE_RECOGNITION: 499 case AudioSource.VOICE_COMMUNICATION: 500 case AudioSource.REMOTE_SUBMIX: 501 case AudioSource.UNPROCESSED: 502 case AudioSource.VOICE_PERFORMANCE: 503 case AudioSource.ECHO_REFERENCE: 504 case AudioSource.RADIO_TUNER: 505 case AudioSource.HOTWORD: 506 case AudioSource.ULTRASOUND: 507 return true; 508 default: 509 return false; 510 } 511 } 512 513 /** @hide */ toLogFriendlyAudioSource(int source)514 public static final String toLogFriendlyAudioSource(int source) { 515 switch(source) { 516 case AudioSource.DEFAULT: 517 return "DEFAULT"; 518 case AudioSource.MIC: 519 return "MIC"; 520 case AudioSource.VOICE_UPLINK: 521 return "VOICE_UPLINK"; 522 case AudioSource.VOICE_DOWNLINK: 523 return "VOICE_DOWNLINK"; 524 case AudioSource.VOICE_CALL: 525 return "VOICE_CALL"; 526 case AudioSource.CAMCORDER: 527 return "CAMCORDER"; 528 case AudioSource.VOICE_RECOGNITION: 529 return "VOICE_RECOGNITION"; 530 case AudioSource.VOICE_COMMUNICATION: 531 return "VOICE_COMMUNICATION"; 532 case AudioSource.REMOTE_SUBMIX: 533 return "REMOTE_SUBMIX"; 534 case AudioSource.UNPROCESSED: 535 return "UNPROCESSED"; 536 case AudioSource.ECHO_REFERENCE: 537 return "ECHO_REFERENCE"; 538 case AudioSource.VOICE_PERFORMANCE: 539 return "VOICE_PERFORMANCE"; 540 case AudioSource.RADIO_TUNER: 541 return "RADIO_TUNER"; 542 case AudioSource.HOTWORD: 543 return "HOTWORD"; 544 case AudioSource.ULTRASOUND: 545 return "ULTRASOUND"; 546 case AudioSource.AUDIO_SOURCE_INVALID: 547 return "AUDIO_SOURCE_INVALID"; 548 default: 549 return "unknown source " + source; 550 } 551 } 552 553 /** 554 * Defines the video source. These constants are used with 555 * {@link MediaRecorder#setVideoSource(int)}. 556 */ 557 public final class VideoSource { 558 /* Do not change these values without updating their counterparts 559 * in include/media/mediarecorder.h! 560 */ VideoSource()561 private VideoSource() {} 562 public static final int DEFAULT = 0; 563 /** Camera video source 564 * <p> 565 * Using the {@link android.hardware.Camera} API as video source. 566 * </p> 567 */ 568 public static final int CAMERA = 1; 569 /** Surface video source 570 * <p> 571 * Using a Surface as video source. 572 * </p><p> 573 * This flag must be used when recording from an 574 * {@link android.hardware.camera2} API source. 575 * </p><p> 576 * When using this video source type, use {@link MediaRecorder#getSurface()} 577 * to retrieve the surface created by MediaRecorder. 578 */ 579 public static final int SURFACE = 2; 580 } 581 582 /** 583 * Defines the output format. These constants are used with 584 * {@link MediaRecorder#setOutputFormat(int)}. 585 */ 586 public final class OutputFormat { 587 /* Do not change these values without updating their counterparts 588 * in include/media/mediarecorder.h! 589 */ OutputFormat()590 private OutputFormat() {} 591 public static final int DEFAULT = 0; 592 /** 3GPP media file format*/ 593 public static final int THREE_GPP = 1; 594 /** MPEG4 media file format*/ 595 public static final int MPEG_4 = 2; 596 597 /** The following formats are audio only .aac or .amr formats */ 598 599 /** 600 * AMR NB file format 601 * @deprecated Deprecated in favor of MediaRecorder.OutputFormat.AMR_NB 602 */ 603 public static final int RAW_AMR = 3; 604 605 /** AMR NB file format */ 606 public static final int AMR_NB = 3; 607 608 /** AMR WB file format */ 609 public static final int AMR_WB = 4; 610 611 /** @hide AAC ADIF file format */ 612 public static final int AAC_ADIF = 5; 613 614 /** AAC ADTS file format */ 615 public static final int AAC_ADTS = 6; 616 617 /** @hide Stream over a socket, limited to a single stream */ 618 public static final int OUTPUT_FORMAT_RTP_AVP = 7; 619 620 /** H.264/AAC data encapsulated in MPEG2/TS */ 621 public static final int MPEG_2_TS = 8; 622 623 /** VP8/VORBIS data in a WEBM container */ 624 public static final int WEBM = 9; 625 626 /** @hide HEIC data in a HEIF container */ 627 public static final int HEIF = 10; 628 629 /** Opus data in a Ogg container */ 630 public static final int OGG = 11; 631 }; 632 633 /** 634 * @hide 635 */ 636 @IntDef({ 637 OutputFormat.DEFAULT, 638 OutputFormat.THREE_GPP, 639 OutputFormat.MPEG_4, 640 OutputFormat.AMR_NB, 641 OutputFormat.AMR_WB, 642 OutputFormat.AAC_ADIF, 643 OutputFormat.AAC_ADTS, 644 OutputFormat.MPEG_2_TS, 645 OutputFormat.WEBM, 646 OutputFormat.HEIF, 647 OutputFormat.OGG, 648 }) 649 @Retention(RetentionPolicy.SOURCE) 650 public @interface OutputFormatValues {} 651 652 /** 653 * Defines the audio encoding. These constants are used with 654 * {@link MediaRecorder#setAudioEncoder(int)}. 655 */ 656 public final class AudioEncoder { 657 /* Do not change these values without updating their counterparts 658 * in include/media/mediarecorder.h! 659 */ AudioEncoder()660 private AudioEncoder() {} 661 public static final int DEFAULT = 0; 662 /** AMR (Narrowband) audio codec */ 663 public static final int AMR_NB = 1; 664 /** AMR (Wideband) audio codec */ 665 public static final int AMR_WB = 2; 666 /** AAC Low Complexity (AAC-LC) audio codec */ 667 public static final int AAC = 3; 668 /** High Efficiency AAC (HE-AAC) audio codec */ 669 public static final int HE_AAC = 4; 670 /** Enhanced Low Delay AAC (AAC-ELD) audio codec */ 671 public static final int AAC_ELD = 5; 672 /** Ogg Vorbis audio codec (Support is optional) */ 673 public static final int VORBIS = 6; 674 /** Opus audio codec */ 675 public static final int OPUS = 7; 676 } 677 678 /** 679 * @hide 680 */ 681 @IntDef({ 682 AudioEncoder.DEFAULT, 683 AudioEncoder.AMR_NB, 684 AudioEncoder.AMR_WB, 685 AudioEncoder.AAC, 686 AudioEncoder.HE_AAC, 687 AudioEncoder.AAC_ELD, 688 AudioEncoder.VORBIS, 689 AudioEncoder.OPUS, 690 }) 691 @Retention(RetentionPolicy.SOURCE) 692 public @interface AudioEncoderValues {} 693 694 /** 695 * Defines the video encoding. These constants are used with 696 * {@link MediaRecorder#setVideoEncoder(int)}. 697 */ 698 public final class VideoEncoder { 699 /* Do not change these values without updating their counterparts 700 * in include/media/mediarecorder.h! 701 */ VideoEncoder()702 private VideoEncoder() {} 703 public static final int DEFAULT = 0; 704 public static final int H263 = 1; 705 public static final int H264 = 2; 706 public static final int MPEG_4_SP = 3; 707 public static final int VP8 = 4; 708 public static final int HEVC = 5; 709 public static final int VP9 = 6; 710 public static final int DOLBY_VISION = 7; 711 public static final int AV1 = 8; 712 } 713 714 /** 715 * @hide 716 */ 717 @IntDef({ 718 VideoEncoder.DEFAULT, 719 VideoEncoder.H263, 720 VideoEncoder.H264, 721 VideoEncoder.MPEG_4_SP, 722 VideoEncoder.VP8, 723 VideoEncoder.HEVC, 724 VideoEncoder.VP9, 725 VideoEncoder.DOLBY_VISION, 726 VideoEncoder.AV1, 727 }) 728 @Retention(RetentionPolicy.SOURCE) 729 public @interface VideoEncoderValues {} 730 731 /** 732 * Sets the audio source to be used for recording. If this method is not 733 * called, the output file will not contain an audio track. The source needs 734 * to be specified before setting recording-parameters or encoders. Call 735 * this only before setOutputFormat(). 736 * 737 * @param audioSource the audio source to use 738 * @throws IllegalStateException if it is called after setOutputFormat() 739 * @see android.media.MediaRecorder.AudioSource 740 */ setAudioSource(@ource int audioSource)741 public native void setAudioSource(@Source int audioSource) 742 throws IllegalStateException; 743 744 /** 745 * Gets the maximum value for audio sources. 746 * @see android.media.MediaRecorder.AudioSource 747 */ getAudioSourceMax()748 public static final int getAudioSourceMax() { 749 return AudioSource.VOICE_PERFORMANCE; 750 } 751 752 /** 753 * Indicates that this capture request is privacy sensitive and that 754 * any concurrent capture is not permitted. 755 * <p> 756 * The default is not privacy sensitive except when the audio source set with 757 * {@link #setAudioSource(int)} is {@link AudioSource#VOICE_COMMUNICATION} or 758 * {@link AudioSource#CAMCORDER}. 759 * <p> 760 * Always takes precedence over default from audio source when set explicitly. 761 * <p> 762 * Using this API is only permitted when the audio source is one of: 763 * <ul> 764 * <li>{@link AudioSource#MIC}</li> 765 * <li>{@link AudioSource#CAMCORDER}</li> 766 * <li>{@link AudioSource#VOICE_RECOGNITION}</li> 767 * <li>{@link AudioSource#VOICE_COMMUNICATION}</li> 768 * <li>{@link AudioSource#UNPROCESSED}</li> 769 * <li>{@link AudioSource#VOICE_PERFORMANCE}</li> 770 * </ul> 771 * Invoking {@link #prepare()} will throw an IOException if this 772 * condition is not met. 773 * <p> 774 * Must be called after {@link #setAudioSource(int)} and before {@link #setOutputFormat(int)}. 775 * @param privacySensitive True if capture from this MediaRecorder must be marked as privacy 776 * sensitive, false otherwise. 777 * @throws IllegalStateException if called before {@link #setAudioSource(int)} 778 * or after {@link #setOutputFormat(int)} 779 */ setPrivacySensitive(boolean privacySensitive)780 public native void setPrivacySensitive(boolean privacySensitive); 781 782 /** 783 * Returns whether this MediaRecorder is marked as privacy sensitive or not with 784 * regard to audio capture. 785 * <p> 786 * See {@link #setPrivacySensitive(boolean)} 787 * <p> 788 * @return true if privacy sensitive, false otherwise 789 */ isPrivacySensitive()790 public native boolean isPrivacySensitive(); 791 792 /** 793 * Sets the video source to be used for recording. If this method is not 794 * called, the output file will not contain an video track. The source needs 795 * to be specified before setting recording-parameters or encoders. Call 796 * this only before setOutputFormat(). 797 * 798 * @param video_source the video source to use 799 * @throws IllegalStateException if it is called after setOutputFormat() 800 * @see android.media.MediaRecorder.VideoSource 801 */ setVideoSource(int video_source)802 public native void setVideoSource(int video_source) 803 throws IllegalStateException; 804 805 /** 806 * Uses the settings from a CamcorderProfile object for recording. This method should 807 * be called after the video AND audio sources are set, and before setOutputFile(). 808 * If a time lapse CamcorderProfile is used, audio related source or recording 809 * parameters are ignored. 810 * 811 * @param profile the CamcorderProfile to use 812 * @see android.media.CamcorderProfile 813 */ setProfile(CamcorderProfile profile)814 public void setProfile(CamcorderProfile profile) { 815 setOutputFormat(profile.fileFormat); 816 setVideoFrameRate(profile.videoFrameRate); 817 setVideoSize(profile.videoFrameWidth, profile.videoFrameHeight); 818 setVideoEncodingBitRate(profile.videoBitRate); 819 setVideoEncoder(profile.videoCodec); 820 if (profile.quality >= CamcorderProfile.QUALITY_TIME_LAPSE_LOW && 821 profile.quality <= CamcorderProfile.QUALITY_TIME_LAPSE_QVGA) { 822 // Nothing needs to be done. Call to setCaptureRate() enables 823 // time lapse video recording. 824 } else { 825 setAudioEncodingBitRate(profile.audioBitRate); 826 setAudioChannels(profile.audioChannels); 827 setAudioSamplingRate(profile.audioSampleRate); 828 setAudioEncoder(profile.audioCodec); 829 } 830 } 831 832 /** 833 * Uses the settings from an AudioProfile for recording. 834 * <p> 835 * This method should be called after the video AND audio sources are set, and before 836 * setOutputFile(). 837 * <p> 838 * This method can be used instead of {@link #setProfile} when using EncoderProfiles. 839 * 840 * @param profile the AudioProfile to use 841 * @see android.media.EncoderProfiles 842 * @see android.media.CamcorderProfile#getAll 843 */ setAudioProfile(@onNull EncoderProfiles.AudioProfile profile)844 public void setAudioProfile(@NonNull EncoderProfiles.AudioProfile profile) { 845 setAudioEncodingBitRate(profile.getBitrate()); 846 setAudioChannels(profile.getChannels()); 847 setAudioSamplingRate(profile.getSampleRate()); 848 setAudioEncoder(profile.getCodec()); 849 } 850 851 /** 852 * Uses the settings from a VideoProfile object for recording. 853 * <p> 854 * This method should be called after the video AND audio sources are set, and before 855 * setOutputFile(). 856 * <p> 857 * This method can be used instead of {@link #setProfile} when using EncoderProfiles. 858 * 859 * @param profile the VideoProfile to use 860 * @see android.media.EncoderProfiles 861 * @see android.media.CamcorderProfile#getAll 862 */ setVideoProfile(@onNull EncoderProfiles.VideoProfile profile)863 public void setVideoProfile(@NonNull EncoderProfiles.VideoProfile profile) { 864 setVideoFrameRate(profile.getFrameRate()); 865 setVideoSize(profile.getWidth(), profile.getHeight()); 866 setVideoEncodingBitRate(profile.getBitrate()); 867 setVideoEncoder(profile.getCodec()); 868 if (profile.getProfile() >= 0) { 869 setVideoEncodingProfileLevel(profile.getProfile(), 0 /* level */); 870 } 871 } 872 873 /** 874 * Set video frame capture rate. This can be used to set a different video frame capture 875 * rate than the recorded video's playback rate. This method also sets the recording mode 876 * to time lapse. In time lapse video recording, only video is recorded. Audio related 877 * parameters are ignored when a time lapse recording session starts, if an application 878 * sets them. 879 * 880 * @param fps Rate at which frames should be captured in frames per second. 881 * The fps can go as low as desired. However the fastest fps will be limited by the hardware. 882 * For resolutions that can be captured by the video camera, the fastest fps can be computed using 883 * {@link android.hardware.Camera.Parameters#getPreviewFpsRange(int[])}. For higher 884 * resolutions the fastest fps may be more restrictive. 885 * Note that the recorder cannot guarantee that frames will be captured at the 886 * given rate due to camera/encoder limitations. However it tries to be as close as 887 * possible. 888 */ setCaptureRate(double fps)889 public void setCaptureRate(double fps) { 890 // Make sure that time lapse is enabled when this method is called. 891 setParameter("time-lapse-enable=1"); 892 setParameter("time-lapse-fps=" + fps); 893 } 894 895 /** 896 * Sets the orientation hint for output video playback. 897 * This method should be called before prepare(). This method will not 898 * trigger the source video frame to rotate during video recording, but to 899 * add a composition matrix containing the rotation angle in the output 900 * video if the output format is OutputFormat.THREE_GPP or 901 * OutputFormat.MPEG_4 so that a video player can choose the proper 902 * orientation for playback. Note that some video players may choose 903 * to ignore the compostion matrix in a video during playback. 904 * 905 * @param degrees the angle to be rotated clockwise in degrees. 906 * The supported angles are 0, 90, 180, and 270 degrees. 907 * @throws IllegalArgumentException if the angle is not supported. 908 * 909 */ setOrientationHint(int degrees)910 public void setOrientationHint(int degrees) { 911 if (degrees != 0 && 912 degrees != 90 && 913 degrees != 180 && 914 degrees != 270) { 915 throw new IllegalArgumentException("Unsupported angle: " + degrees); 916 } 917 setParameter("video-param-rotation-angle-degrees=" + degrees); 918 } 919 920 /** 921 * Set and store the geodata (latitude and longitude) in the output file. 922 * This method should be called before prepare(). The geodata is 923 * stored in udta box if the output format is OutputFormat.THREE_GPP 924 * or OutputFormat.MPEG_4, and is ignored for other output formats. 925 * The geodata is stored according to ISO-6709 standard. 926 * 927 * @param latitude latitude in degrees. Its value must be in the 928 * range [-90, 90]. 929 * @param longitude longitude in degrees. Its value must be in the 930 * range [-180, 180]. 931 * 932 * @throws IllegalArgumentException if the given latitude or 933 * longitude is out of range. 934 * 935 */ setLocation(float latitude, float longitude)936 public void setLocation(float latitude, float longitude) { 937 int latitudex10000 = (int) (latitude * 10000 + 0.5); 938 int longitudex10000 = (int) (longitude * 10000 + 0.5); 939 940 if (latitudex10000 > 900000 || latitudex10000 < -900000) { 941 String msg = "Latitude: " + latitude + " out of range."; 942 throw new IllegalArgumentException(msg); 943 } 944 if (longitudex10000 > 1800000 || longitudex10000 < -1800000) { 945 String msg = "Longitude: " + longitude + " out of range"; 946 throw new IllegalArgumentException(msg); 947 } 948 949 setParameter("param-geotag-latitude=" + latitudex10000); 950 setParameter("param-geotag-longitude=" + longitudex10000); 951 } 952 953 /** 954 * Sets the format of the output file produced during recording. Call this 955 * after setAudioSource()/setVideoSource() but before prepare(). 956 * 957 * <p>It is recommended to always use 3GP format when using the H.263 958 * video encoder and AMR audio encoder. Using an MPEG-4 container format 959 * may confuse some desktop players.</p> 960 * 961 * @param output_format the output format to use. The output format 962 * needs to be specified before setting recording-parameters or encoders. 963 * @throws IllegalStateException if it is called after prepare() or before 964 * setAudioSource()/setVideoSource(). 965 * @see android.media.MediaRecorder.OutputFormat 966 */ setOutputFormat(@utputFormatValues int output_format)967 public native void setOutputFormat(@OutputFormatValues int output_format) 968 throws IllegalStateException; 969 970 /** 971 * Sets the width and height of the video to be captured. Must be called 972 * after setVideoSource(). Call this after setOutputFormat() but before 973 * prepare(). 974 * 975 * @param width the width of the video to be captured 976 * @param height the height of the video to be captured 977 * @throws IllegalStateException if it is called after 978 * prepare() or before setOutputFormat() 979 */ setVideoSize(int width, int height)980 public native void setVideoSize(int width, int height) 981 throws IllegalStateException; 982 983 /** 984 * Sets the frame rate of the video to be captured. Must be called 985 * after setVideoSource(). Call this after setOutputFormat() but before 986 * prepare(). 987 * 988 * <p>NOTE: On some devices that have auto-frame rate, this sets the 989 * maximum frame rate, not a constant frame rate. Actual frame rate 990 * will vary according to lighting conditions.</p> 991 * 992 * @param rate the number of frames per second of video to capture 993 * @throws IllegalStateException if it is called after 994 * prepare() or before setOutputFormat(). 995 */ setVideoFrameRate(int rate)996 public native void setVideoFrameRate(int rate) throws IllegalStateException; 997 998 /** 999 * Sets the maximum duration (in ms) of the recording session. 1000 * Call this after setOutputFormat() but before prepare(). 1001 * After recording reaches the specified duration, a notification 1002 * will be sent to the {@link android.media.MediaRecorder.OnInfoListener} 1003 * with a "what" code of {@link #MEDIA_RECORDER_INFO_MAX_DURATION_REACHED} 1004 * and recording will be stopped. Stopping happens asynchronously, there 1005 * is no guarantee that the recorder will have stopped by the time the 1006 * listener is notified. 1007 * 1008 * <p>When using MPEG-4 container ({@link #setOutputFormat(int)} with 1009 * {@link OutputFormat#MPEG_4}), it is recommended to set maximum duration that fits the use 1010 * case. Setting a larger than required duration may result in a larger than needed output file 1011 * because of space reserved for MOOV box expecting large movie data in this recording session. 1012 * Unused space of MOOV box is turned into FREE box in the output file.</p> 1013 * 1014 * @param max_duration_ms the maximum duration in ms (if zero or negative, disables the duration limit) 1015 * 1016 */ setMaxDuration(int max_duration_ms)1017 public native void setMaxDuration(int max_duration_ms) throws IllegalArgumentException; 1018 1019 /** 1020 * Sets the maximum filesize (in bytes) of the recording session. 1021 * Call this after setOutputFormat() but before prepare(). 1022 * After recording reaches the specified filesize, a notification 1023 * will be sent to the {@link android.media.MediaRecorder.OnInfoListener} 1024 * with a "what" code of {@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED} 1025 * and recording will be stopped. Stopping happens asynchronously, there 1026 * is no guarantee that the recorder will have stopped by the time the 1027 * listener is notified. 1028 * 1029 * <p>When using MPEG-4 container ({@link #setOutputFormat(int)} with 1030 * {@link OutputFormat#MPEG_4}), it is recommended to set maximum filesize that fits the use 1031 * case. Setting a larger than required filesize may result in a larger than needed output file 1032 * because of space reserved for MOOV box expecting large movie data in this recording session. 1033 * Unused space of MOOV box is turned into FREE box in the output file.</p> 1034 * 1035 * @param max_filesize_bytes the maximum filesize in bytes (if zero or negative, disables the limit) 1036 * 1037 */ setMaxFileSize(long max_filesize_bytes)1038 public native void setMaxFileSize(long max_filesize_bytes) throws IllegalArgumentException; 1039 1040 /** 1041 * Sets the audio encoder to be used for recording. If this method is not 1042 * called, the output file will not contain an audio track. Call this after 1043 * setOutputFormat() but before prepare(). 1044 * 1045 * @param audio_encoder the audio encoder to use. 1046 * @throws IllegalStateException if it is called before 1047 * setOutputFormat() or after prepare(). 1048 * @see android.media.MediaRecorder.AudioEncoder 1049 */ setAudioEncoder(@udioEncoderValues int audio_encoder)1050 public native void setAudioEncoder(@AudioEncoderValues int audio_encoder) 1051 throws IllegalStateException; 1052 1053 /** 1054 * Sets the video encoder to be used for recording. If this method is not 1055 * called, the output file will not contain an video track. Call this after 1056 * setOutputFormat() and before prepare(). 1057 * 1058 * @param video_encoder the video encoder to use. 1059 * @throws IllegalStateException if it is called before 1060 * setOutputFormat() or after prepare() 1061 * @see android.media.MediaRecorder.VideoEncoder 1062 */ setVideoEncoder(@ideoEncoderValues int video_encoder)1063 public native void setVideoEncoder(@VideoEncoderValues int video_encoder) 1064 throws IllegalStateException; 1065 1066 /** 1067 * Sets the audio sampling rate for recording. Call this method before prepare(). 1068 * Prepare() may perform additional checks on the parameter to make sure whether 1069 * the specified audio sampling rate is applicable. The sampling rate really depends 1070 * on the format for the audio recording, as well as the capabilities of the platform. 1071 * For instance, the sampling rate supported by AAC audio coding standard ranges 1072 * from 8 to 96 kHz, the sampling rate supported by AMRNB is 8kHz, and the sampling 1073 * rate supported by AMRWB is 16kHz. Please consult with the related audio coding 1074 * standard for the supported audio sampling rate. 1075 * 1076 * @param samplingRate the sampling rate for audio in samples per second. 1077 */ setAudioSamplingRate(int samplingRate)1078 public void setAudioSamplingRate(int samplingRate) { 1079 if (samplingRate <= 0) { 1080 throw new IllegalArgumentException("Audio sampling rate is not positive"); 1081 } 1082 setParameter("audio-param-sampling-rate=" + samplingRate); 1083 } 1084 1085 /** 1086 * Sets the number of audio channels for recording. Call this method before prepare(). 1087 * Prepare() may perform additional checks on the parameter to make sure whether the 1088 * specified number of audio channels are applicable. 1089 * 1090 * @param numChannels the number of audio channels. Usually it is either 1 (mono) or 2 1091 * (stereo). 1092 */ setAudioChannels(int numChannels)1093 public void setAudioChannels(int numChannels) { 1094 if (numChannels <= 0) { 1095 throw new IllegalArgumentException("Number of channels is not positive"); 1096 } 1097 mChannelCount = numChannels; 1098 setParameter("audio-param-number-of-channels=" + numChannels); 1099 } 1100 1101 /** 1102 * Sets the audio encoding bit rate for recording. Call this method before prepare(). 1103 * Prepare() may perform additional checks on the parameter to make sure whether the 1104 * specified bit rate is applicable, and sometimes the passed bitRate will be clipped 1105 * internally to ensure the audio recording can proceed smoothly based on the 1106 * capabilities of the platform. 1107 * 1108 * @param bitRate the audio encoding bit rate in bits per second. 1109 */ setAudioEncodingBitRate(int bitRate)1110 public void setAudioEncodingBitRate(int bitRate) { 1111 if (bitRate <= 0) { 1112 throw new IllegalArgumentException("Audio encoding bit rate is not positive"); 1113 } 1114 setParameter("audio-param-encoding-bitrate=" + bitRate); 1115 } 1116 1117 /** 1118 * Sets the video encoding bit rate for recording. Call this method before prepare(). 1119 * Prepare() may perform additional checks on the parameter to make sure whether the 1120 * specified bit rate is applicable, and sometimes the passed bitRate will be 1121 * clipped internally to ensure the video recording can proceed smoothly based on 1122 * the capabilities of the platform. 1123 * 1124 * <p> 1125 * NB: the actual bitrate and other encoding characteristics may be affected by 1126 * the minimum quality floor behavior introduced in 1127 * {@link android.os.Build.VERSION_CODES#S}. More detail on how and where this 1128 * impacts video encoding can be found in the 1129 * {@link MediaCodec} page and looking for "quality floor" (near the top of the page). 1130 * 1131 * @param bitRate the video encoding bit rate in bits per second. 1132 */ setVideoEncodingBitRate(int bitRate)1133 public void setVideoEncodingBitRate(int bitRate) { 1134 if (bitRate <= 0) { 1135 throw new IllegalArgumentException("Video encoding bit rate is not positive"); 1136 } 1137 setParameter("video-param-encoding-bitrate=" + bitRate); 1138 } 1139 1140 /** 1141 * Sets the desired video encoding profile and level for recording. The profile and level 1142 * must be valid for the video encoder set by {@link #setVideoEncoder}. This method can 1143 * called before or after {@link #setVideoEncoder} but it must be called before {@link #prepare}. 1144 * {@code prepare()} may perform additional checks on the parameter to make sure that the specified 1145 * profile and level are applicable, and sometimes the passed profile or level will be 1146 * discarded due to codec capablity or to ensure the video recording can proceed smoothly 1147 * based on the capabilities of the platform. <br>Application can also use the 1148 * {@link MediaCodecInfo.CodecCapabilities#profileLevels} to query applicable combination of profile 1149 * and level for the corresponding format. Note that the requested profile/level may not be supported by 1150 * the codec that is actually being used by this MediaRecorder instance. 1151 * @param profile declared in {@link MediaCodecInfo.CodecProfileLevel}. 1152 * @param level declared in {@link MediaCodecInfo.CodecProfileLevel}. 1153 * @throws IllegalArgumentException when an invalid profile or level value is used. 1154 */ setVideoEncodingProfileLevel(int profile, int level)1155 public void setVideoEncodingProfileLevel(int profile, int level) { 1156 if (profile < 0) { 1157 throw new IllegalArgumentException("Video encoding profile is not positive"); 1158 } 1159 if (level < 0) { 1160 throw new IllegalArgumentException("Video encoding level is not positive"); 1161 } 1162 setParameter("video-param-encoder-profile=" + profile); 1163 setParameter("video-param-encoder-level=" + level); 1164 } 1165 1166 /** 1167 * Currently not implemented. It does nothing. 1168 * @deprecated Time lapse mode video recording using camera still image capture 1169 * is not desirable, and will not be supported. 1170 * @hide 1171 */ setAuxiliaryOutputFile(FileDescriptor fd)1172 public void setAuxiliaryOutputFile(FileDescriptor fd) 1173 { 1174 Log.w(TAG, "setAuxiliaryOutputFile(FileDescriptor) is no longer supported."); 1175 } 1176 1177 /** 1178 * Currently not implemented. It does nothing. 1179 * @deprecated Time lapse mode video recording using camera still image capture 1180 * is not desirable, and will not be supported. 1181 * @hide 1182 */ setAuxiliaryOutputFile(String path)1183 public void setAuxiliaryOutputFile(String path) 1184 { 1185 Log.w(TAG, "setAuxiliaryOutputFile(String) is no longer supported."); 1186 } 1187 1188 /** 1189 * Pass in the file descriptor of the file to be written. Call this after 1190 * setOutputFormat() but before prepare(). 1191 * 1192 * @param fd an open file descriptor to be written into. 1193 * @throws IllegalStateException if it is called before 1194 * setOutputFormat() or after prepare() 1195 */ setOutputFile(FileDescriptor fd)1196 public void setOutputFile(FileDescriptor fd) throws IllegalStateException 1197 { 1198 mPath = null; 1199 mFile = null; 1200 mFd = fd; 1201 } 1202 1203 /** 1204 * Pass in the file object to be written. Call this after setOutputFormat() but before prepare(). 1205 * File should be seekable. After setting the next output file, application should not use the 1206 * file until {@link #stop}. Application is responsible for cleaning up unused files after 1207 * {@link #stop} is called. 1208 * 1209 * @param file the file object to be written into. 1210 */ setOutputFile(File file)1211 public void setOutputFile(File file) 1212 { 1213 mPath = null; 1214 mFd = null; 1215 mFile = file; 1216 } 1217 1218 /** 1219 * Sets the next output file descriptor to be used when the maximum filesize is reached 1220 * on the prior output {@link #setOutputFile} or {@link #setNextOutputFile}). File descriptor 1221 * must be seekable and writable. After setting the next output file, application should not 1222 * use the file referenced by this file descriptor until {@link #stop}. It is the application's 1223 * responsibility to close the file descriptor. It is safe to do so as soon as this call returns. 1224 * Application must call this after receiving on the 1225 * {@link android.media.MediaRecorder.OnInfoListener} a "what" code of 1226 * {@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_APPROACHING} and before receiving a "what" code of 1227 * {@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED}. The file is not used until switching to 1228 * that output. Application will receive{@link #MEDIA_RECORDER_INFO_NEXT_OUTPUT_FILE_STARTED} 1229 * when the next output file is used. Application will not be able to set a new output file if 1230 * the previous one has not been used. Application is responsible for cleaning up unused files 1231 * after {@link #stop} is called. 1232 * 1233 * @param fd an open file descriptor to be written into. 1234 * @throws IllegalStateException if it is called before prepare(). 1235 * @throws IOException if setNextOutputFile fails otherwise. 1236 */ setNextOutputFile(FileDescriptor fd)1237 public void setNextOutputFile(FileDescriptor fd) throws IOException 1238 { 1239 _setNextOutputFile(fd); 1240 } 1241 1242 /** 1243 * Sets the path of the output file to be produced. Call this after 1244 * setOutputFormat() but before prepare(). 1245 * 1246 * @param path The pathname to use. 1247 * @throws IllegalStateException if it is called before 1248 * setOutputFormat() or after prepare() 1249 */ setOutputFile(String path)1250 public void setOutputFile(String path) throws IllegalStateException 1251 { 1252 mFd = null; 1253 mFile = null; 1254 mPath = path; 1255 } 1256 1257 /** 1258 * Sets the next output file to be used when the maximum filesize is reached on the prior 1259 * output {@link #setOutputFile} or {@link #setNextOutputFile}). File should be seekable. 1260 * After setting the next output file, application should not use the file until {@link #stop}. 1261 * Application must call this after receiving on the 1262 * {@link android.media.MediaRecorder.OnInfoListener} a "what" code of 1263 * {@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_APPROACHING} and before receiving a "what" code of 1264 * {@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED}. The file is not used until switching to 1265 * that output. Application will receive {@link #MEDIA_RECORDER_INFO_NEXT_OUTPUT_FILE_STARTED} 1266 * when the next output file is used. Application will not be able to set a new output file if 1267 * the previous one has not been used. Application is responsible for cleaning up unused files 1268 * after {@link #stop} is called. 1269 * 1270 * @param file The file to use. 1271 * @throws IllegalStateException if it is called before prepare(). 1272 * @throws IOException if setNextOutputFile fails otherwise. 1273 */ setNextOutputFile(File file)1274 public void setNextOutputFile(File file) throws IOException 1275 { 1276 RandomAccessFile f = new RandomAccessFile(file, "rw"); 1277 try { 1278 _setNextOutputFile(f.getFD()); 1279 } finally { 1280 f.close(); 1281 } 1282 } 1283 1284 // native implementation _setOutputFile(FileDescriptor fd)1285 private native void _setOutputFile(FileDescriptor fd) throws IllegalStateException, IOException; _setNextOutputFile(FileDescriptor fd)1286 private native void _setNextOutputFile(FileDescriptor fd) throws IllegalStateException, IOException; 1287 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) _prepare()1288 private native void _prepare() throws IllegalStateException, IOException; 1289 1290 /** 1291 * Prepares the recorder to begin capturing and encoding data. This method 1292 * must be called after setting up the desired audio and video sources, 1293 * encoders, file format, etc., but before start(). 1294 * 1295 * @throws IllegalStateException if it is called after 1296 * start() or before setOutputFormat(). 1297 * @throws IOException if prepare fails otherwise. 1298 */ prepare()1299 public void prepare() throws IllegalStateException, IOException 1300 { 1301 if (mPath != null) { 1302 RandomAccessFile file = new RandomAccessFile(mPath, "rw"); 1303 try { 1304 _setOutputFile(file.getFD()); 1305 } finally { 1306 file.close(); 1307 } 1308 } else if (mFd != null) { 1309 _setOutputFile(mFd); 1310 } else if (mFile != null) { 1311 RandomAccessFile file = new RandomAccessFile(mFile, "rw"); 1312 try { 1313 _setOutputFile(file.getFD()); 1314 } finally { 1315 file.close(); 1316 } 1317 } else { 1318 throw new IOException("No valid output file"); 1319 } 1320 1321 _prepare(); 1322 } 1323 1324 /** 1325 * Begins capturing and encoding data to the file specified with 1326 * setOutputFile(). Call this after prepare(). 1327 * 1328 * <p>Since API level 13, if applications set a camera via 1329 * {@link #setCamera(Camera)}, the apps can use the camera after this method 1330 * call. The apps do not need to lock the camera again. However, if this 1331 * method fails, the apps should still lock the camera back. The apps should 1332 * not start another recording session during recording. 1333 * 1334 * @throws IllegalStateException if it is called before 1335 * prepare() or when the camera is already in use by another app. 1336 */ start()1337 public native void start() throws IllegalStateException; 1338 1339 /** 1340 * Stops recording. Call this after start(). Once recording is stopped, 1341 * you will have to configure it again as if it has just been constructed. 1342 * Note that a RuntimeException is intentionally thrown to the 1343 * application, if no valid audio/video data has been received when stop() 1344 * is called. This happens if stop() is called immediately after 1345 * start(). The failure lets the application take action accordingly to 1346 * clean up the output file (delete the output file, for instance), since 1347 * the output file is not properly constructed when this happens. 1348 * 1349 * @throws IllegalStateException if it is called before start() 1350 */ stop()1351 public native void stop() throws IllegalStateException; 1352 1353 /** 1354 * Pauses recording. Call this after start(). You may resume recording 1355 * with resume() without reconfiguration, as opposed to stop(). It does 1356 * nothing if the recording is already paused. 1357 * 1358 * When the recording is paused and resumed, the resulting output would 1359 * be as if nothing happend during paused period, immediately switching 1360 * to the resumed scene. 1361 * 1362 * @throws IllegalStateException if it is called before start() or after 1363 * stop() 1364 */ pause()1365 public native void pause() throws IllegalStateException; 1366 1367 /** 1368 * Resumes recording. Call this after start(). It does nothing if the 1369 * recording is not paused. 1370 * 1371 * @throws IllegalStateException if it is called before start() or after 1372 * stop() 1373 * @see android.media.MediaRecorder#pause 1374 */ resume()1375 public native void resume() throws IllegalStateException; 1376 1377 /** 1378 * Restarts the MediaRecorder to its idle state. After calling 1379 * this method, you will have to configure it again as if it had just been 1380 * constructed. 1381 */ reset()1382 public void reset() { 1383 native_reset(); 1384 1385 // make sure none of the listeners get called anymore 1386 mEventHandler.removeCallbacksAndMessages(null); 1387 } 1388 1389 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) native_reset()1390 private native void native_reset(); 1391 1392 /** 1393 * Returns the maximum absolute amplitude that was sampled since the last 1394 * call to this method. Call this only after the setAudioSource(). 1395 * 1396 * @return the maximum absolute amplitude measured since the last call, or 1397 * 0 when called for the first time 1398 * @throws IllegalStateException if it is called before 1399 * the audio source has been set. 1400 */ getMaxAmplitude()1401 public native int getMaxAmplitude() throws IllegalStateException; 1402 1403 /* Do not change this value without updating its counterpart 1404 * in include/media/mediarecorder.h or mediaplayer.h! 1405 */ 1406 /** Unspecified media recorder error. 1407 * @see android.media.MediaRecorder.OnErrorListener 1408 */ 1409 public static final int MEDIA_RECORDER_ERROR_UNKNOWN = 1; 1410 /** Media server died. In this case, the application must release the 1411 * MediaRecorder object and instantiate a new one. 1412 * @see android.media.MediaRecorder.OnErrorListener 1413 */ 1414 public static final int MEDIA_ERROR_SERVER_DIED = 100; 1415 1416 /** 1417 * Interface definition for a callback to be invoked when an error 1418 * occurs while recording. 1419 */ 1420 public interface OnErrorListener 1421 { 1422 /** 1423 * Called when an error occurs while recording. 1424 * 1425 * @param mr the MediaRecorder that encountered the error 1426 * @param what the type of error that has occurred: 1427 * <ul> 1428 * <li>{@link #MEDIA_RECORDER_ERROR_UNKNOWN} 1429 * <li>{@link #MEDIA_ERROR_SERVER_DIED} 1430 * </ul> 1431 * @param extra an extra code, specific to the error type 1432 */ onError(MediaRecorder mr, int what, int extra)1433 void onError(MediaRecorder mr, int what, int extra); 1434 } 1435 1436 /** 1437 * Register a callback to be invoked when an error occurs while 1438 * recording. 1439 * 1440 * @param l the callback that will be run 1441 */ setOnErrorListener(OnErrorListener l)1442 public void setOnErrorListener(OnErrorListener l) 1443 { 1444 mOnErrorListener = l; 1445 } 1446 1447 /* Do not change these values without updating their counterparts 1448 * in include/media/mediarecorder.h! 1449 */ 1450 /** Unspecified media recorder info. 1451 * @see android.media.MediaRecorder.OnInfoListener 1452 */ 1453 public static final int MEDIA_RECORDER_INFO_UNKNOWN = 1; 1454 /** A maximum duration had been setup and has now been reached. 1455 * @see android.media.MediaRecorder.OnInfoListener 1456 */ 1457 public static final int MEDIA_RECORDER_INFO_MAX_DURATION_REACHED = 800; 1458 /** A maximum filesize had been setup and has now been reached. 1459 * Note: This event will not be sent if application already set 1460 * next output file through {@link #setNextOutputFile}. 1461 * @see android.media.MediaRecorder.OnInfoListener 1462 */ 1463 public static final int MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED = 801; 1464 /** A maximum filesize had been setup and current recorded file size 1465 * has reached 90% of the limit. This is sent once per file upon 1466 * reaching/passing the 90% limit. To continue the recording, applicaiton 1467 * should use {@link #setNextOutputFile} to set the next output file. 1468 * Otherwise, recording will stop when reaching maximum file size. 1469 * @see android.media.MediaRecorder.OnInfoListener 1470 */ 1471 public static final int MEDIA_RECORDER_INFO_MAX_FILESIZE_APPROACHING = 802; 1472 /** A maximum filesize had been reached and MediaRecorder has switched 1473 * output to a new file set by application {@link #setNextOutputFile}. 1474 * For best practice, application should use this event to keep track 1475 * of whether the file previously set has been used or not. 1476 * @see android.media.MediaRecorder.OnInfoListener 1477 */ 1478 public static final int MEDIA_RECORDER_INFO_NEXT_OUTPUT_FILE_STARTED = 803; 1479 1480 /** informational events for individual tracks, for testing purpose. 1481 * The track informational event usually contains two parts in the ext1 1482 * arg of the onInfo() callback: bit 31-28 contains the track id; and 1483 * the rest of the 28 bits contains the informational event defined here. 1484 * For example, ext1 = (1 << 28 | MEDIA_RECORDER_TRACK_INFO_TYPE) if the 1485 * track id is 1 for informational event MEDIA_RECORDER_TRACK_INFO_TYPE; 1486 * while ext1 = (0 << 28 | MEDIA_RECORDER_TRACK_INFO_TYPE) if the track 1487 * id is 0 for informational event MEDIA_RECORDER_TRACK_INFO_TYPE. The 1488 * application should extract the track id and the type of informational 1489 * event from ext1, accordingly. 1490 * 1491 * FIXME: 1492 * Please update the comment for onInfo also when these 1493 * events are unhidden so that application knows how to extract the track 1494 * id and the informational event type from onInfo callback. 1495 * 1496 * {@hide} 1497 */ 1498 public static final int MEDIA_RECORDER_TRACK_INFO_LIST_START = 1000; 1499 /** Signal the completion of the track for the recording session. 1500 * {@hide} 1501 */ 1502 public static final int MEDIA_RECORDER_TRACK_INFO_COMPLETION_STATUS = 1000; 1503 /** Indicate the recording progress in time (ms) during recording. 1504 * {@hide} 1505 */ 1506 public static final int MEDIA_RECORDER_TRACK_INFO_PROGRESS_IN_TIME = 1001; 1507 /** Indicate the track type: 0 for Audio and 1 for Video. 1508 * {@hide} 1509 */ 1510 public static final int MEDIA_RECORDER_TRACK_INFO_TYPE = 1002; 1511 /** Provide the track duration information. 1512 * {@hide} 1513 */ 1514 public static final int MEDIA_RECORDER_TRACK_INFO_DURATION_MS = 1003; 1515 /** Provide the max chunk duration in time (ms) for the given track. 1516 * {@hide} 1517 */ 1518 public static final int MEDIA_RECORDER_TRACK_INFO_MAX_CHUNK_DUR_MS = 1004; 1519 /** Provide the total number of recordd frames. 1520 * {@hide} 1521 */ 1522 public static final int MEDIA_RECORDER_TRACK_INFO_ENCODED_FRAMES = 1005; 1523 /** Provide the max spacing between neighboring chunks for the given track. 1524 * {@hide} 1525 */ 1526 public static final int MEDIA_RECORDER_TRACK_INTER_CHUNK_TIME_MS = 1006; 1527 /** Provide the elapsed time measuring from the start of the recording 1528 * till the first output frame of the given track is received, excluding 1529 * any intentional start time offset of a recording session for the 1530 * purpose of eliminating the recording sound in the recorded file. 1531 * {@hide} 1532 */ 1533 public static final int MEDIA_RECORDER_TRACK_INFO_INITIAL_DELAY_MS = 1007; 1534 /** Provide the start time difference (delay) betweeen this track and 1535 * the start of the movie. 1536 * {@hide} 1537 */ 1538 public static final int MEDIA_RECORDER_TRACK_INFO_START_OFFSET_MS = 1008; 1539 /** Provide the total number of data (in kilo-bytes) encoded. 1540 * {@hide} 1541 */ 1542 public static final int MEDIA_RECORDER_TRACK_INFO_DATA_KBYTES = 1009; 1543 /** 1544 * {@hide} 1545 */ 1546 public static final int MEDIA_RECORDER_TRACK_INFO_LIST_END = 2000; 1547 1548 1549 /** 1550 * Interface definition of a callback to be invoked to communicate some 1551 * info and/or warning about the recording. 1552 */ 1553 public interface OnInfoListener 1554 { 1555 /** 1556 * Called to indicate an info or a warning during recording. 1557 * 1558 * @param mr the MediaRecorder the info pertains to 1559 * @param what the type of info or warning that has occurred 1560 * <ul> 1561 * <li>{@link #MEDIA_RECORDER_INFO_UNKNOWN} 1562 * <li>{@link #MEDIA_RECORDER_INFO_MAX_DURATION_REACHED} 1563 * <li>{@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED} 1564 * </ul> 1565 * @param extra an extra code, specific to the info type 1566 */ onInfo(MediaRecorder mr, int what, int extra)1567 void onInfo(MediaRecorder mr, int what, int extra); 1568 } 1569 1570 /** 1571 * Register a callback to be invoked when an informational event occurs while 1572 * recording. 1573 * 1574 * @param listener the callback that will be run 1575 */ setOnInfoListener(OnInfoListener listener)1576 public void setOnInfoListener(OnInfoListener listener) 1577 { 1578 mOnInfoListener = listener; 1579 } 1580 1581 private class EventHandler extends Handler 1582 { 1583 private MediaRecorder mMediaRecorder; 1584 EventHandler(MediaRecorder mr, Looper looper)1585 public EventHandler(MediaRecorder mr, Looper looper) { 1586 super(looper); 1587 mMediaRecorder = mr; 1588 } 1589 1590 /* Do not change these values without updating their counterparts 1591 * in include/media/mediarecorder.h! 1592 */ 1593 private static final int MEDIA_RECORDER_EVENT_LIST_START = 1; 1594 private static final int MEDIA_RECORDER_EVENT_ERROR = 1; 1595 private static final int MEDIA_RECORDER_EVENT_INFO = 2; 1596 private static final int MEDIA_RECORDER_EVENT_LIST_END = 99; 1597 1598 /* Events related to individual tracks */ 1599 private static final int MEDIA_RECORDER_TRACK_EVENT_LIST_START = 100; 1600 private static final int MEDIA_RECORDER_TRACK_EVENT_ERROR = 100; 1601 private static final int MEDIA_RECORDER_TRACK_EVENT_INFO = 101; 1602 private static final int MEDIA_RECORDER_TRACK_EVENT_LIST_END = 1000; 1603 1604 private static final int MEDIA_RECORDER_AUDIO_ROUTING_CHANGED = 10000; 1605 1606 @Override handleMessage(Message msg)1607 public void handleMessage(Message msg) { 1608 if (mMediaRecorder.mNativeContext == 0) { 1609 Log.w(TAG, "mediarecorder went away with unhandled events"); 1610 return; 1611 } 1612 switch(msg.what) { 1613 case MEDIA_RECORDER_EVENT_ERROR: 1614 case MEDIA_RECORDER_TRACK_EVENT_ERROR: 1615 if (mOnErrorListener != null) 1616 mOnErrorListener.onError(mMediaRecorder, msg.arg1, msg.arg2); 1617 1618 return; 1619 1620 case MEDIA_RECORDER_EVENT_INFO: 1621 case MEDIA_RECORDER_TRACK_EVENT_INFO: 1622 if (mOnInfoListener != null) 1623 mOnInfoListener.onInfo(mMediaRecorder, msg.arg1, msg.arg2); 1624 1625 return; 1626 1627 case MEDIA_RECORDER_AUDIO_ROUTING_CHANGED: 1628 AudioManager.resetAudioPortGeneration(); 1629 synchronized (mRoutingChangeListeners) { 1630 for (NativeRoutingEventHandlerDelegate delegate 1631 : mRoutingChangeListeners.values()) { 1632 delegate.notifyClient(); 1633 } 1634 } 1635 return; 1636 1637 default: 1638 Log.e(TAG, "Unknown message type " + msg.what); 1639 return; 1640 } 1641 } 1642 } 1643 1644 //-------------------------------------------------------------------------- 1645 // Explicit Routing 1646 //-------------------- 1647 private AudioDeviceInfo mPreferredDevice = null; 1648 1649 /** 1650 * Specifies an audio device (via an {@link AudioDeviceInfo} object) to route 1651 * the input from this MediaRecorder. 1652 * @param deviceInfo The {@link AudioDeviceInfo} specifying the audio source. 1653 * If deviceInfo is null, default routing is restored. 1654 * @return true if succesful, false if the specified {@link AudioDeviceInfo} is non-null and 1655 * does not correspond to a valid audio input device. 1656 */ 1657 @Override setPreferredDevice(AudioDeviceInfo deviceInfo)1658 public boolean setPreferredDevice(AudioDeviceInfo deviceInfo) { 1659 if (deviceInfo != null && !deviceInfo.isSource()) { 1660 return false; 1661 } 1662 int preferredDeviceId = deviceInfo != null ? deviceInfo.getId() : 0; 1663 boolean status = native_setInputDevice(preferredDeviceId); 1664 if (status == true) { 1665 synchronized (this) { 1666 mPreferredDevice = deviceInfo; 1667 } 1668 } 1669 return status; 1670 } 1671 1672 /** 1673 * Returns the selected input device specified by {@link #setPreferredDevice}. Note that this 1674 * is not guaranteed to correspond to the actual device being used for recording. 1675 */ 1676 @Override getPreferredDevice()1677 public AudioDeviceInfo getPreferredDevice() { 1678 synchronized (this) { 1679 return mPreferredDevice; 1680 } 1681 } 1682 1683 /** 1684 * Returns an {@link AudioDeviceInfo} identifying the current routing of this MediaRecorder 1685 * Note: The query is only valid if the MediaRecorder is currently recording. 1686 * If the recorder is not recording, the returned device can be null or correspond to previously 1687 * selected device when the recorder was last active. 1688 */ 1689 @Override getRoutedDevice()1690 public AudioDeviceInfo getRoutedDevice() { 1691 int deviceId = native_getRoutedDeviceId(); 1692 if (deviceId == 0) { 1693 return null; 1694 } 1695 return AudioManager.getDeviceForPortId(deviceId, AudioManager.GET_DEVICES_INPUTS); 1696 } 1697 1698 /* 1699 * Call BEFORE adding a routing callback handler or AFTER removing a routing callback handler. 1700 */ 1701 @GuardedBy("mRoutingChangeListeners") enableNativeRoutingCallbacksLocked(boolean enabled)1702 private void enableNativeRoutingCallbacksLocked(boolean enabled) { 1703 if (mRoutingChangeListeners.size() == 0) { 1704 native_enableDeviceCallback(enabled); 1705 } 1706 } 1707 1708 /** 1709 * The list of AudioRouting.OnRoutingChangedListener interfaces added (with 1710 * {@link #addOnRoutingChangedListener(android.media.AudioRouting.OnRoutingChangedListener, Handler)} 1711 * by an app to receive (re)routing notifications. 1712 */ 1713 @GuardedBy("mRoutingChangeListeners") 1714 private ArrayMap<AudioRouting.OnRoutingChangedListener, 1715 NativeRoutingEventHandlerDelegate> mRoutingChangeListeners = new ArrayMap<>(); 1716 1717 /** 1718 * Adds an {@link AudioRouting.OnRoutingChangedListener} to receive notifications of routing 1719 * changes on this MediaRecorder. 1720 * @param listener The {@link AudioRouting.OnRoutingChangedListener} interface to receive 1721 * notifications of rerouting events. 1722 * @param handler Specifies the {@link Handler} object for the thread on which to execute 1723 * the callback. If <code>null</code>, the handler on the main looper will be used. 1724 */ 1725 @Override addOnRoutingChangedListener(AudioRouting.OnRoutingChangedListener listener, Handler handler)1726 public void addOnRoutingChangedListener(AudioRouting.OnRoutingChangedListener listener, 1727 Handler handler) { 1728 synchronized (mRoutingChangeListeners) { 1729 if (listener != null && !mRoutingChangeListeners.containsKey(listener)) { 1730 enableNativeRoutingCallbacksLocked(true); 1731 mRoutingChangeListeners.put( 1732 listener, new NativeRoutingEventHandlerDelegate(this, listener, 1733 handler != null ? handler : mEventHandler)); 1734 } 1735 } 1736 } 1737 1738 /** 1739 * Removes an {@link AudioRouting.OnRoutingChangedListener} which has been previously added 1740 * to receive rerouting notifications. 1741 * @param listener The previously added {@link AudioRouting.OnRoutingChangedListener} interface 1742 * to remove. 1743 */ 1744 @Override removeOnRoutingChangedListener(AudioRouting.OnRoutingChangedListener listener)1745 public void removeOnRoutingChangedListener(AudioRouting.OnRoutingChangedListener listener) { 1746 synchronized (mRoutingChangeListeners) { 1747 if (mRoutingChangeListeners.containsKey(listener)) { 1748 mRoutingChangeListeners.remove(listener); 1749 enableNativeRoutingCallbacksLocked(false); 1750 } 1751 } 1752 } 1753 native_setInputDevice(int deviceId)1754 private native final boolean native_setInputDevice(int deviceId); native_getRoutedDeviceId()1755 private native final int native_getRoutedDeviceId(); native_enableDeviceCallback(boolean enabled)1756 private native final void native_enableDeviceCallback(boolean enabled); 1757 1758 //-------------------------------------------------------------------------- 1759 // Microphone information 1760 //-------------------- 1761 /** 1762 * Return A lists of {@link MicrophoneInfo} representing the active microphones. 1763 * By querying channel mapping for each active microphone, developer can know how 1764 * the microphone is used by each channels or a capture stream. 1765 * 1766 * @return a lists of {@link MicrophoneInfo} representing the active microphones 1767 * @throws IOException if an error occurs 1768 */ getActiveMicrophones()1769 public List<MicrophoneInfo> getActiveMicrophones() throws IOException { 1770 ArrayList<MicrophoneInfo> activeMicrophones = new ArrayList<>(); 1771 int status = native_getActiveMicrophones(activeMicrophones); 1772 if (status != AudioManager.SUCCESS) { 1773 if (status != AudioManager.ERROR_INVALID_OPERATION) { 1774 Log.e(TAG, "getActiveMicrophones failed:" + status); 1775 } 1776 Log.i(TAG, "getActiveMicrophones failed, fallback on routed device info"); 1777 } 1778 AudioManager.setPortIdForMicrophones(activeMicrophones); 1779 1780 // Use routed device when there is not information returned by hal. 1781 if (activeMicrophones.size() == 0) { 1782 AudioDeviceInfo device = getRoutedDevice(); 1783 if (device != null) { 1784 MicrophoneInfo microphone = AudioManager.microphoneInfoFromAudioDeviceInfo(device); 1785 ArrayList<Pair<Integer, Integer>> channelMapping = new ArrayList<>(); 1786 for (int i = 0; i < mChannelCount; i++) { 1787 channelMapping.add(new Pair(i, MicrophoneInfo.CHANNEL_MAPPING_DIRECT)); 1788 } 1789 microphone.setChannelMapping(channelMapping); 1790 activeMicrophones.add(microphone); 1791 } 1792 } 1793 return activeMicrophones; 1794 } 1795 native_getActiveMicrophones( ArrayList<MicrophoneInfo> activeMicrophones)1796 private native final int native_getActiveMicrophones( 1797 ArrayList<MicrophoneInfo> activeMicrophones); 1798 1799 //-------------------------------------------------------------------------- 1800 // MicrophoneDirection 1801 //-------------------- 1802 /** 1803 * Specifies the logical microphone (for processing). 1804 * 1805 * @param direction Direction constant. 1806 * @return true if sucessful. 1807 */ setPreferredMicrophoneDirection(@irectionMode int direction)1808 public boolean setPreferredMicrophoneDirection(@DirectionMode int direction) { 1809 return native_setPreferredMicrophoneDirection(direction) == 0; 1810 } 1811 1812 /** 1813 * Specifies the zoom factor (i.e. the field dimension) for the selected microphone 1814 * (for processing). The selected microphone is determined by the use-case for the stream. 1815 * 1816 * @param zoom the desired field dimension of microphone capture. Range is from -1 (wide angle), 1817 * though 0 (no zoom) to 1 (maximum zoom). 1818 * @return true if sucessful. 1819 */ setPreferredMicrophoneFieldDimension( @loatRangefrom = -1.0, to = 1.0) float zoom)1820 public boolean setPreferredMicrophoneFieldDimension( 1821 @FloatRange(from = -1.0, to = 1.0) float zoom) { 1822 Preconditions.checkArgument( 1823 zoom >= -1 && zoom <= 1, "Argument must fall between -1 & 1 (inclusive)"); 1824 return native_setPreferredMicrophoneFieldDimension(zoom) == 0; 1825 } 1826 native_setPreferredMicrophoneDirection(int direction)1827 private native int native_setPreferredMicrophoneDirection(int direction); native_setPreferredMicrophoneFieldDimension(float zoom)1828 private native int native_setPreferredMicrophoneFieldDimension(float zoom); 1829 1830 //-------------------------------------------------------------------------- 1831 // Implementation of AudioRecordingMonitor interface 1832 //-------------------- 1833 1834 AudioRecordingMonitorImpl mRecordingInfoImpl = 1835 new AudioRecordingMonitorImpl((AudioRecordingMonitorClient) this); 1836 1837 /** 1838 * Register a callback to be notified of audio capture changes via a 1839 * {@link AudioManager.AudioRecordingCallback}. A callback is received when the capture path 1840 * configuration changes (pre-processing, format, sampling rate...) or capture is 1841 * silenced/unsilenced by the system. 1842 * @param executor {@link Executor} to handle the callbacks. 1843 * @param cb non-null callback to register 1844 */ registerAudioRecordingCallback(@onNull @allbackExecutor Executor executor, @NonNull AudioManager.AudioRecordingCallback cb)1845 public void registerAudioRecordingCallback(@NonNull @CallbackExecutor Executor executor, 1846 @NonNull AudioManager.AudioRecordingCallback cb) { 1847 mRecordingInfoImpl.registerAudioRecordingCallback(executor, cb); 1848 } 1849 1850 /** 1851 * Unregister an audio recording callback previously registered with 1852 * {@link #registerAudioRecordingCallback(Executor, AudioManager.AudioRecordingCallback)}. 1853 * @param cb non-null callback to unregister 1854 */ unregisterAudioRecordingCallback(@onNull AudioManager.AudioRecordingCallback cb)1855 public void unregisterAudioRecordingCallback(@NonNull AudioManager.AudioRecordingCallback cb) { 1856 mRecordingInfoImpl.unregisterAudioRecordingCallback(cb); 1857 } 1858 1859 /** 1860 * Returns the current active audio recording for this audio recorder. 1861 * @return a valid {@link AudioRecordingConfiguration} if this recorder is active 1862 * or null otherwise. 1863 * @see AudioRecordingConfiguration 1864 */ getActiveRecordingConfiguration()1865 public @Nullable AudioRecordingConfiguration getActiveRecordingConfiguration() { 1866 return mRecordingInfoImpl.getActiveRecordingConfiguration(); 1867 } 1868 1869 //--------------------------------------------------------- 1870 // Implementation of AudioRecordingMonitorClient interface 1871 //-------------------- 1872 /** 1873 * @hide 1874 */ getPortId()1875 public int getPortId() { 1876 if (mNativeContext == 0) { 1877 return 0; 1878 } 1879 return native_getPortId(); 1880 } 1881 native_getPortId()1882 private native int native_getPortId(); 1883 1884 /** 1885 * Called from native code when an interesting event happens. This method 1886 * just uses the EventHandler system to post the event back to the main app thread. 1887 * We use a weak reference to the original MediaRecorder object so that the native 1888 * code is safe from the object disappearing from underneath it. (This is 1889 * the cookie passed to native_setup().) 1890 */ postEventFromNative(Object mediarecorder_ref, int what, int arg1, int arg2, Object obj)1891 private static void postEventFromNative(Object mediarecorder_ref, 1892 int what, int arg1, int arg2, Object obj) 1893 { 1894 MediaRecorder mr = (MediaRecorder)((WeakReference)mediarecorder_ref).get(); 1895 if (mr == null) { 1896 return; 1897 } 1898 1899 if (mr.mEventHandler != null) { 1900 Message m = mr.mEventHandler.obtainMessage(what, arg1, arg2, obj); 1901 mr.mEventHandler.sendMessage(m); 1902 } 1903 } 1904 1905 /** 1906 * Releases resources associated with this MediaRecorder object. 1907 * It is good practice to call this method when you're done 1908 * using the MediaRecorder. In particular, whenever an Activity 1909 * of an application is paused (its onPause() method is called), 1910 * or stopped (its onStop() method is called), this method should be 1911 * invoked to release the MediaRecorder object, unless the application 1912 * has a special need to keep the object around. In addition to 1913 * unnecessary resources (such as memory and instances of codecs) 1914 * being held, failure to call this method immediately if a 1915 * MediaRecorder object is no longer needed may also lead to 1916 * continuous battery consumption for mobile devices, and recording 1917 * failure for other applications if no multiple instances of the 1918 * same codec are supported on a device. Even if multiple instances 1919 * of the same codec are supported, some performance degradation 1920 * may be expected when unnecessary multiple instances are used 1921 * at the same time. 1922 */ release()1923 public native void release(); 1924 1925 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) native_init()1926 private static native final void native_init(); 1927 1928 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, 1929 publicAlternatives = "{@link MediaRecorder}") native_setup(Object mediarecorderThis, String clientName, String opPackageName)1930 private void native_setup(Object mediarecorderThis, 1931 String clientName, String opPackageName) throws IllegalStateException { 1932 AttributionSource attributionSource = AttributionSource.myAttributionSource() 1933 .withPackageName(opPackageName); 1934 try (ScopedParcelState attributionSourceState = attributionSource.asScopedParcelState()) { 1935 native_setup(mediarecorderThis, clientName, attributionSourceState.getParcel()); 1936 } 1937 } 1938 native_setup(Object mediarecorderThis, String clientName, @NonNull Parcel attributionSource)1939 private native void native_setup(Object mediarecorderThis, 1940 String clientName, @NonNull Parcel attributionSource) 1941 throws IllegalStateException; 1942 1943 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) native_finalize()1944 private native void native_finalize(); 1945 1946 @UnsupportedAppUsage setParameter(String nameValuePair)1947 private native void setParameter(String nameValuePair); 1948 1949 /** 1950 * Return Metrics data about the current Mediarecorder instance. 1951 * 1952 * @return a {@link PersistableBundle} containing the set of attributes and values 1953 * available for the media being generated by this instance of 1954 * MediaRecorder. 1955 * The attributes are descibed in {@link MetricsConstants}. 1956 * 1957 * Additional vendor-specific fields may also be present in 1958 * the return value. 1959 */ getMetrics()1960 public PersistableBundle getMetrics() { 1961 PersistableBundle bundle = native_getMetrics(); 1962 return bundle; 1963 } 1964 native_getMetrics()1965 private native PersistableBundle native_getMetrics(); 1966 1967 @Override finalize()1968 protected void finalize() { native_finalize(); } 1969 1970 public final static class MetricsConstants 1971 { MetricsConstants()1972 private MetricsConstants() {} 1973 1974 /** 1975 * Key to extract the audio bitrate 1976 * from the {@link MediaRecorder#getMetrics} return. 1977 * The value is an integer. 1978 */ 1979 public static final String AUDIO_BITRATE = "android.media.mediarecorder.audio-bitrate"; 1980 1981 /** 1982 * Key to extract the number of audio channels 1983 * from the {@link MediaRecorder#getMetrics} return. 1984 * The value is an integer. 1985 */ 1986 public static final String AUDIO_CHANNELS = "android.media.mediarecorder.audio-channels"; 1987 1988 /** 1989 * Key to extract the audio samplerate 1990 * from the {@link MediaRecorder#getMetrics} return. 1991 * The value is an integer. 1992 */ 1993 public static final String AUDIO_SAMPLERATE = "android.media.mediarecorder.audio-samplerate"; 1994 1995 /** 1996 * Key to extract the audio timescale 1997 * from the {@link MediaRecorder#getMetrics} return. 1998 * The value is an integer. 1999 */ 2000 public static final String AUDIO_TIMESCALE = "android.media.mediarecorder.audio-timescale"; 2001 2002 /** 2003 * Key to extract the video capture frame rate 2004 * from the {@link MediaRecorder#getMetrics} return. 2005 * The value is a double. 2006 */ 2007 public static final String CAPTURE_FPS = "android.media.mediarecorder.capture-fps"; 2008 2009 /** 2010 * Key to extract the video capture framerate enable value 2011 * from the {@link MediaRecorder#getMetrics} return. 2012 * The value is an integer. 2013 */ 2014 public static final String CAPTURE_FPS_ENABLE = "android.media.mediarecorder.capture-fpsenable"; 2015 2016 /** 2017 * Key to extract the intended playback frame rate 2018 * from the {@link MediaRecorder#getMetrics} return. 2019 * The value is an integer. 2020 */ 2021 public static final String FRAMERATE = "android.media.mediarecorder.frame-rate"; 2022 2023 /** 2024 * Key to extract the height (in pixels) of the captured video 2025 * from the {@link MediaRecorder#getMetrics} return. 2026 * The value is an integer. 2027 */ 2028 public static final String HEIGHT = "android.media.mediarecorder.height"; 2029 2030 /** 2031 * Key to extract the recorded movies time units 2032 * from the {@link MediaRecorder#getMetrics} return. 2033 * The value is an integer. 2034 * A value of 1000 indicates that the movie's timing is in milliseconds. 2035 */ 2036 public static final String MOVIE_TIMESCALE = "android.media.mediarecorder.movie-timescale"; 2037 2038 /** 2039 * Key to extract the rotation (in degrees) to properly orient the video 2040 * from the {@link MediaRecorder#getMetrics} return. 2041 * The value is an integer. 2042 */ 2043 public static final String ROTATION = "android.media.mediarecorder.rotation"; 2044 2045 /** 2046 * Key to extract the video bitrate from being used 2047 * from the {@link MediaRecorder#getMetrics} return. 2048 * The value is an integer. 2049 */ 2050 public static final String VIDEO_BITRATE = "android.media.mediarecorder.video-bitrate"; 2051 2052 /** 2053 * Key to extract the value for how often video iframes are generated 2054 * from the {@link MediaRecorder#getMetrics} return. 2055 * The value is an integer. 2056 */ 2057 public static final String VIDEO_IFRAME_INTERVAL = "android.media.mediarecorder.video-iframe-interval"; 2058 2059 /** 2060 * Key to extract the video encoding level 2061 * from the {@link MediaRecorder#getMetrics} return. 2062 * The value is an integer. 2063 */ 2064 public static final String VIDEO_LEVEL = "android.media.mediarecorder.video-encoder-level"; 2065 2066 /** 2067 * Key to extract the video encoding profile 2068 * from the {@link MediaRecorder#getMetrics} return. 2069 * The value is an integer. 2070 */ 2071 public static final String VIDEO_PROFILE = "android.media.mediarecorder.video-encoder-profile"; 2072 2073 /** 2074 * Key to extract the recorded video time units 2075 * from the {@link MediaRecorder#getMetrics} return. 2076 * The value is an integer. 2077 * A value of 1000 indicates that the video's timing is in milliseconds. 2078 */ 2079 public static final String VIDEO_TIMESCALE = "android.media.mediarecorder.video-timescale"; 2080 2081 /** 2082 * Key to extract the width (in pixels) of the captured video 2083 * from the {@link MediaRecorder#getMetrics} return. 2084 * The value is an integer. 2085 */ 2086 public static final String WIDTH = "android.media.mediarecorder.width"; 2087 2088 } 2089 } 2090