AudioRecord.java revision 6809afe1c26f0044adf2be414fcaede9024289a6
1/* 2 * Copyright (C) 2008 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 java.lang.ref.WeakReference; 20import java.lang.IllegalArgumentException; 21import java.lang.IllegalStateException; 22import java.nio.ByteBuffer; 23 24import android.os.Handler; 25import android.os.Looper; 26import android.os.Message; 27import android.util.Log; 28 29/** 30 * The AudioRecord class manages the audio resources for Java applications 31 * to record audio from the audio input hardware of the platform. This is 32 * achieved by "pulling" (reading) the data from the AudioRecord object. The 33 * application is responsible for polling the AudioRecord object in time using one of 34 * the following three methods: {@link #read(byte[],int, int)}, {@link #read(short[], int, int)} 35 * or {@link #read(ByteBuffer, int)}. The choice of which method to use will be based 36 * on the audio data storage format that is the most convenient for the user of AudioRecord. 37 * <p>Upon creation, an AudioRecord object initializes its associated audio buffer that it will 38 * fill with the new audio data. The size of this buffer, specified during the construction, 39 * determines how long an AudioRecord can record before "over-running" data that has not 40 * been read yet. Data should be read from the audio hardware in chunks of sizes inferior to 41 * the total recording buffer size. 42 */ 43public class AudioRecord 44{ 45 //--------------------------------------------------------- 46 // Constants 47 //-------------------- 48 /** 49 * indicates AudioRecord state is not successfully initialized. 50 */ 51 public static final int STATE_UNINITIALIZED = 0; 52 /** 53 * indicates AudioRecord state is ready to be used 54 */ 55 public static final int STATE_INITIALIZED = 1; 56 57 /** 58 * indicates AudioRecord recording state is not recording 59 */ 60 public static final int RECORDSTATE_STOPPED = 1; // matches SL_RECORDSTATE_STOPPED 61 /** 62 * indicates AudioRecord recording state is recording 63 */ 64 public static final int RECORDSTATE_RECORDING = 3;// matches SL_RECORDSTATE_RECORDING 65 66 // Error codes: 67 // to keep in sync with frameworks/base/core/jni/android_media_AudioRecord.cpp 68 /** 69 * Denotes a successful operation. 70 */ 71 public static final int SUCCESS = 0; 72 /** 73 * Denotes a generic operation failure. 74 */ 75 public static final int ERROR = -1; 76 /** 77 * Denotes a failure due to the use of an invalid value. 78 */ 79 public static final int ERROR_BAD_VALUE = -2; 80 /** 81 * Denotes a failure due to the improper use of a method. 82 */ 83 public static final int ERROR_INVALID_OPERATION = -3; 84 85 private static final int AUDIORECORD_ERROR_SETUP_ZEROFRAMECOUNT = -16; 86 private static final int AUDIORECORD_ERROR_SETUP_INVALIDCHANNELMASK = -17; 87 private static final int AUDIORECORD_ERROR_SETUP_INVALIDFORMAT = -18; 88 private static final int AUDIORECORD_ERROR_SETUP_INVALIDSOURCE = -19; 89 private static final int AUDIORECORD_ERROR_SETUP_NATIVEINITFAILED = -20; 90 91 // Events: 92 // to keep in sync with frameworks/base/include/media/AudioRecord.h 93 /** 94 * Event id denotes when record head has reached a previously set marker. 95 */ 96 private static final int NATIVE_EVENT_MARKER = 2; 97 /** 98 * Event id denotes when previously set update period has elapsed during recording. 99 */ 100 private static final int NATIVE_EVENT_NEW_POS = 3; 101 102 private final static String TAG = "AudioRecord-Java"; 103 104 105 //--------------------------------------------------------- 106 // Used exclusively by native code 107 //-------------------- 108 /** 109 * Accessed by native methods: provides access to C++ AudioRecord object 110 */ 111 @SuppressWarnings("unused") 112 private int mNativeRecorderInJavaObj; 113 114 /** 115 * Accessed by native methods: provides access to the callback data. 116 */ 117 @SuppressWarnings("unused") 118 private int mNativeCallbackCookie; 119 120 121 //--------------------------------------------------------- 122 // Member variables 123 //-------------------- 124 /** 125 * The audio data sampling rate in Hz. 126 */ 127 private int mSampleRate = 22050; 128 /** 129 * The number of input audio channels (1 is mono, 2 is stereo) 130 */ 131 private int mChannelCount = 1; 132 /** 133 * The audio channel mask 134 */ 135 private int mChannels = AudioFormat.CHANNEL_IN_MONO; 136 /** 137 * The current audio channel configuration 138 */ 139 private int mChannelConfiguration = AudioFormat.CHANNEL_IN_MONO; 140 /** 141 * The encoding of the audio samples. 142 * @see AudioFormat#ENCODING_PCM_8BIT 143 * @see AudioFormat#ENCODING_PCM_16BIT 144 */ 145 private int mAudioFormat = AudioFormat.ENCODING_PCM_16BIT; 146 /** 147 * Where the audio data is recorded from. 148 */ 149 private int mRecordSource = MediaRecorder.AudioSource.DEFAULT; 150 /** 151 * Indicates the state of the AudioRecord instance. 152 */ 153 private int mState = STATE_UNINITIALIZED; 154 /** 155 * Indicates the recording state of the AudioRecord instance. 156 */ 157 private int mRecordingState = RECORDSTATE_STOPPED; 158 /** 159 * Lock to make sure mRecordingState updates are reflecting the actual state of the object. 160 */ 161 private final Object mRecordingStateLock = new Object(); 162 /** 163 * The listener the AudioRecord notifies when the record position reaches a marker 164 * or for periodic updates during the progression of the record head. 165 * @see #setRecordPositionUpdateListener(OnRecordPositionUpdateListener) 166 * @see #setRecordPositionUpdateListener(OnRecordPositionUpdateListener, Handler) 167 */ 168 private OnRecordPositionUpdateListener mPositionListener = null; 169 /** 170 * Lock to protect position listener updates against event notifications 171 */ 172 private final Object mPositionListenerLock = new Object(); 173 /** 174 * Handler for marker events coming from the native code 175 */ 176 private NativeEventHandler mEventHandler = null; 177 /** 178 * Looper associated with the thread that creates the AudioRecord instance 179 */ 180 private Looper mInitializationLooper = null; 181 /** 182 * Size of the native audio buffer. 183 */ 184 private int mNativeBufferSizeInBytes = 0; 185 /** 186 * Audio session ID 187 */ 188 private int mSessionId = 0; 189 190 //--------------------------------------------------------- 191 // Constructor, Finalize 192 //-------------------- 193 /** 194 * Class constructor. 195 * @param audioSource the recording source. See {@link MediaRecorder.AudioSource} for 196 * recording source definitions. 197 * @param sampleRateInHz the sample rate expressed in Hertz. 44100Hz is currently the only 198 * rate that is guaranteed to work on all devices, but other rates such as 22050, 199 * 16000, and 11025 may work on some devices. 200 * @param channelConfig describes the configuration of the audio channels. 201 * See {@link AudioFormat#CHANNEL_IN_MONO} and 202 * {@link AudioFormat#CHANNEL_IN_STEREO}. {@link AudioFormat#CHANNEL_IN_MONO} is guaranteed 203 * to work on all devices. 204 * @param audioFormat the format in which the audio data is represented. 205 * See {@link AudioFormat#ENCODING_PCM_16BIT} and 206 * {@link AudioFormat#ENCODING_PCM_8BIT} 207 * @param bufferSizeInBytes the total size (in bytes) of the buffer where audio data is written 208 * to during the recording. New audio data can be read from this buffer in smaller chunks 209 * than this size. See {@link #getMinBufferSize(int, int, int)} to determine the minimum 210 * required buffer size for the successful creation of an AudioRecord instance. Using values 211 * smaller than getMinBufferSize() will result in an initialization failure. 212 * @throws java.lang.IllegalArgumentException 213 */ 214 public AudioRecord(int audioSource, int sampleRateInHz, int channelConfig, int audioFormat, 215 int bufferSizeInBytes) 216 throws IllegalArgumentException { 217 mState = STATE_UNINITIALIZED; 218 mRecordingState = RECORDSTATE_STOPPED; 219 220 // remember which looper is associated with the AudioRecord instanciation 221 if ((mInitializationLooper = Looper.myLooper()) == null) { 222 mInitializationLooper = Looper.getMainLooper(); 223 } 224 225 audioParamCheck(audioSource, sampleRateInHz, channelConfig, audioFormat); 226 227 audioBuffSizeCheck(bufferSizeInBytes); 228 229 // native initialization 230 int[] session = new int[1]; 231 session[0] = 0; 232 //TODO: update native initialization when information about hardware init failure 233 // due to capture device already open is available. 234 int initResult = native_setup( new WeakReference<AudioRecord>(this), 235 mRecordSource, mSampleRate, mChannels, mAudioFormat, mNativeBufferSizeInBytes, 236 session); 237 if (initResult != SUCCESS) { 238 loge("Error code "+initResult+" when initializing native AudioRecord object."); 239 return; // with mState == STATE_UNINITIALIZED 240 } 241 242 mSessionId = session[0]; 243 244 mState = STATE_INITIALIZED; 245 } 246 247 248 // Convenience method for the constructor's parameter checks. 249 // This is where constructor IllegalArgumentException-s are thrown 250 // postconditions: 251 // mRecordSource is valid 252 // mChannelCount is valid 253 // mChannels is valid 254 // mAudioFormat is valid 255 // mSampleRate is valid 256 private void audioParamCheck(int audioSource, int sampleRateInHz, 257 int channelConfig, int audioFormat) { 258 259 //-------------- 260 // audio source 261 if ( (audioSource < MediaRecorder.AudioSource.DEFAULT) || 262 (audioSource > MediaRecorder.getAudioSourceMax()) ) { 263 throw (new IllegalArgumentException("Invalid audio source.")); 264 } else { 265 mRecordSource = audioSource; 266 } 267 268 //-------------- 269 // sample rate 270 if ( (sampleRateInHz < 4000) || (sampleRateInHz > 48000) ) { 271 throw (new IllegalArgumentException(sampleRateInHz 272 + "Hz is not a supported sample rate.")); 273 } else { 274 mSampleRate = sampleRateInHz; 275 } 276 277 //-------------- 278 // channel config 279 mChannelConfiguration = channelConfig; 280 281 switch (channelConfig) { 282 case AudioFormat.CHANNEL_IN_DEFAULT: // AudioFormat.CHANNEL_CONFIGURATION_DEFAULT 283 case AudioFormat.CHANNEL_IN_MONO: 284 case AudioFormat.CHANNEL_CONFIGURATION_MONO: 285 mChannelCount = 1; 286 mChannels = AudioFormat.CHANNEL_IN_MONO; 287 break; 288 case AudioFormat.CHANNEL_IN_STEREO: 289 case AudioFormat.CHANNEL_CONFIGURATION_STEREO: 290 mChannelCount = 2; 291 mChannels = AudioFormat.CHANNEL_IN_STEREO; 292 break; 293 case (AudioFormat.CHANNEL_IN_FRONT | AudioFormat.CHANNEL_IN_BACK): 294 mChannelCount = 2; 295 mChannels = channelConfig; 296 break; 297 default: 298 mChannelCount = 0; 299 mChannels = AudioFormat.CHANNEL_INVALID; 300 mChannelConfiguration = AudioFormat.CHANNEL_INVALID; 301 throw (new IllegalArgumentException("Unsupported channel configuration.")); 302 } 303 304 //-------------- 305 // audio format 306 switch (audioFormat) { 307 case AudioFormat.ENCODING_DEFAULT: 308 mAudioFormat = AudioFormat.ENCODING_PCM_16BIT; 309 break; 310 case AudioFormat.ENCODING_PCM_16BIT: 311 case AudioFormat.ENCODING_PCM_8BIT: 312 mAudioFormat = audioFormat; 313 break; 314 default: 315 mAudioFormat = AudioFormat.ENCODING_INVALID; 316 throw (new IllegalArgumentException("Unsupported sample encoding." 317 + " Should be ENCODING_PCM_8BIT or ENCODING_PCM_16BIT.")); 318 } 319 } 320 321 322 // Convenience method for the contructor's audio buffer size check. 323 // preconditions: 324 // mChannelCount is valid 325 // mAudioFormat is AudioFormat.ENCODING_PCM_8BIT OR AudioFormat.ENCODING_PCM_16BIT 326 // postcondition: 327 // mNativeBufferSizeInBytes is valid (multiple of frame size, positive) 328 private void audioBuffSizeCheck(int audioBufferSize) { 329 // NB: this section is only valid with PCM data. 330 // To update when supporting compressed formats 331 int frameSizeInBytes = mChannelCount 332 * (mAudioFormat == AudioFormat.ENCODING_PCM_8BIT ? 1 : 2); 333 if ((audioBufferSize % frameSizeInBytes != 0) || (audioBufferSize < 1)) { 334 throw (new IllegalArgumentException("Invalid audio buffer size.")); 335 } 336 337 mNativeBufferSizeInBytes = audioBufferSize; 338 } 339 340 341 342 /** 343 * Releases the native AudioRecord resources. 344 * The object can no longer be used and the reference should be set to null 345 * after a call to release() 346 */ 347 public void release() { 348 try { 349 stop(); 350 } catch(IllegalStateException ise) { 351 // don't raise an exception, we're releasing the resources. 352 } 353 native_release(); 354 mState = STATE_UNINITIALIZED; 355 } 356 357 358 @Override 359 protected void finalize() { 360 native_finalize(); 361 } 362 363 364 //-------------------------------------------------------------------------- 365 // Getters 366 //-------------------- 367 /** 368 * Returns the configured audio data sample rate in Hz 369 */ 370 public int getSampleRate() { 371 return mSampleRate; 372 } 373 374 /** 375 * Returns the audio recording source. 376 * @see MediaRecorder.AudioSource 377 */ 378 public int getAudioSource() { 379 return mRecordSource; 380 } 381 382 /** 383 * Returns the configured audio data format. See {@link AudioFormat#ENCODING_PCM_16BIT} 384 * and {@link AudioFormat#ENCODING_PCM_8BIT}. 385 */ 386 public int getAudioFormat() { 387 return mAudioFormat; 388 } 389 390 /** 391 * Returns the configured channel configuration. 392 * See {@link AudioFormat#CHANNEL_IN_MONO} 393 * and {@link AudioFormat#CHANNEL_IN_STEREO}. 394 */ 395 public int getChannelConfiguration() { 396 return mChannelConfiguration; 397 } 398 399 /** 400 * Returns the configured number of channels. 401 */ 402 public int getChannelCount() { 403 return mChannelCount; 404 } 405 406 /** 407 * Returns the state of the AudioRecord instance. This is useful after the 408 * AudioRecord instance has been created to check if it was initialized 409 * properly. This ensures that the appropriate hardware resources have been 410 * acquired. 411 * @see AudioRecord#STATE_INITIALIZED 412 * @see AudioRecord#STATE_UNINITIALIZED 413 */ 414 public int getState() { 415 return mState; 416 } 417 418 /** 419 * Returns the recording state of the AudioRecord instance. 420 * @see AudioRecord#RECORDSTATE_STOPPED 421 * @see AudioRecord#RECORDSTATE_RECORDING 422 */ 423 public int getRecordingState() { 424 return mRecordingState; 425 } 426 427 /** 428 * Returns the notification marker position expressed in frames. 429 */ 430 public int getNotificationMarkerPosition() { 431 return native_get_marker_pos(); 432 } 433 434 /** 435 * Returns the notification update period expressed in frames. 436 */ 437 public int getPositionNotificationPeriod() { 438 return native_get_pos_update_period(); 439 } 440 441 /** 442 * Returns the minimum buffer size required for the successful creation of an AudioRecord 443 * object. 444 * Note that this size doesn't guarantee a smooth recording under load, and higher values 445 * should be chosen according to the expected frequency at which the AudioRecord instance 446 * will be polled for new data. 447 * @param sampleRateInHz the sample rate expressed in Hertz. 448 * @param channelConfig describes the configuration of the audio channels. 449 * See {@link AudioFormat#CHANNEL_IN_MONO} and 450 * {@link AudioFormat#CHANNEL_IN_STEREO} 451 * @param audioFormat the format in which the audio data is represented. 452 * See {@link AudioFormat#ENCODING_PCM_16BIT}. 453 * @return {@link #ERROR_BAD_VALUE} if the recording parameters are not supported by the 454 * hardware, or an invalid parameter was passed, 455 * or {@link #ERROR} if the implementation was unable to query the hardware for its 456 * output properties, 457 * or the minimum buffer size expressed in bytes. 458 * @see #AudioRecord(int, int, int, int, int) for more information on valid 459 * configuration values. 460 */ 461 static public int getMinBufferSize(int sampleRateInHz, int channelConfig, int audioFormat) { 462 int channelCount = 0; 463 switch (channelConfig) { 464 case AudioFormat.CHANNEL_IN_DEFAULT: // AudioFormat.CHANNEL_CONFIGURATION_DEFAULT 465 case AudioFormat.CHANNEL_IN_MONO: 466 case AudioFormat.CHANNEL_CONFIGURATION_MONO: 467 channelCount = 1; 468 break; 469 case AudioFormat.CHANNEL_IN_STEREO: 470 case AudioFormat.CHANNEL_CONFIGURATION_STEREO: 471 case (AudioFormat.CHANNEL_IN_FRONT | AudioFormat.CHANNEL_IN_BACK): 472 channelCount = 2; 473 break; 474 case AudioFormat.CHANNEL_INVALID: 475 default: 476 loge("getMinBufferSize(): Invalid channel configuration."); 477 return AudioRecord.ERROR_BAD_VALUE; 478 } 479 480 // PCM_8BIT is not supported at the moment 481 if (audioFormat != AudioFormat.ENCODING_PCM_16BIT) { 482 loge("getMinBufferSize(): Invalid audio format."); 483 return AudioRecord.ERROR_BAD_VALUE; 484 } 485 486 int size = native_get_min_buff_size(sampleRateInHz, channelCount, audioFormat); 487 if (size == 0) { 488 return AudioRecord.ERROR_BAD_VALUE; 489 } 490 else if (size == -1) { 491 return AudioRecord.ERROR; 492 } 493 else { 494 return size; 495 } 496 } 497 498 /** 499 * Returns the audio session ID. 500 * 501 * @return the ID of the audio session this AudioRecord belongs to. 502 */ 503 public int getAudioSessionId() { 504 return mSessionId; 505 } 506 507 //--------------------------------------------------------- 508 // Transport control methods 509 //-------------------- 510 /** 511 * Starts recording from the AudioRecord instance. 512 * @throws IllegalStateException 513 */ 514 public void startRecording() 515 throws IllegalStateException { 516 if (mState != STATE_INITIALIZED) { 517 throw(new IllegalStateException("startRecording() called on an " 518 +"uninitialized AudioRecord.")); 519 } 520 521 // start recording 522 synchronized(mRecordingStateLock) { 523 if (native_start(MediaSyncEvent.SYNC_EVENT_NONE, 0) == SUCCESS) { 524 mRecordingState = RECORDSTATE_RECORDING; 525 } 526 } 527 } 528 529 /** 530 * Starts recording from the AudioRecord instance when the specified synchronization event 531 * occurs on the specified audio session. 532 * @throws IllegalStateException 533 * @param syncEvent event that triggers the capture. 534 * @see MediaSyncEvent 535 */ 536 public void startRecording(MediaSyncEvent syncEvent) 537 throws IllegalStateException { 538 if (mState != STATE_INITIALIZED) { 539 throw(new IllegalStateException("startRecording() called on an " 540 +"uninitialized AudioRecord.")); 541 } 542 543 // start recording 544 synchronized(mRecordingStateLock) { 545 if (native_start(syncEvent.getType(), syncEvent.getAudioSessionId()) == SUCCESS) { 546 mRecordingState = RECORDSTATE_RECORDING; 547 } 548 } 549 } 550 551 /** 552 * Stops recording. 553 * @throws IllegalStateException 554 */ 555 public void stop() 556 throws IllegalStateException { 557 if (mState != STATE_INITIALIZED) { 558 throw(new IllegalStateException("stop() called on an uninitialized AudioRecord.")); 559 } 560 561 // stop recording 562 synchronized(mRecordingStateLock) { 563 native_stop(); 564 mRecordingState = RECORDSTATE_STOPPED; 565 } 566 } 567 568 569 //--------------------------------------------------------- 570 // Audio data supply 571 //-------------------- 572 /** 573 * Reads audio data from the audio hardware for recording into a buffer. 574 * @param audioData the array to which the recorded audio data is written. 575 * @param offsetInBytes index in audioData from which the data is written expressed in bytes. 576 * @param sizeInBytes the number of requested bytes. 577 * @return the number of bytes that were read or or {@link #ERROR_INVALID_OPERATION} 578 * if the object wasn't properly initialized, or {@link #ERROR_BAD_VALUE} if 579 * the parameters don't resolve to valid data and indexes. 580 * The number of bytes will not exceed sizeInBytes. 581 */ 582 public int read(byte[] audioData, int offsetInBytes, int sizeInBytes) { 583 if (mState != STATE_INITIALIZED) { 584 return ERROR_INVALID_OPERATION; 585 } 586 587 if ( (audioData == null) || (offsetInBytes < 0 ) || (sizeInBytes < 0) 588 || (offsetInBytes + sizeInBytes > audioData.length)) { 589 return ERROR_BAD_VALUE; 590 } 591 592 return native_read_in_byte_array(audioData, offsetInBytes, sizeInBytes); 593 } 594 595 596 /** 597 * Reads audio data from the audio hardware for recording into a buffer. 598 * @param audioData the array to which the recorded audio data is written. 599 * @param offsetInShorts index in audioData from which the data is written expressed in shorts. 600 * @param sizeInShorts the number of requested shorts. 601 * @return the number of shorts that were read or or {@link #ERROR_INVALID_OPERATION} 602 * if the object wasn't properly initialized, or {@link #ERROR_BAD_VALUE} if 603 * the parameters don't resolve to valid data and indexes. 604 * The number of shorts will not exceed sizeInShorts. 605 */ 606 public int read(short[] audioData, int offsetInShorts, int sizeInShorts) { 607 if (mState != STATE_INITIALIZED) { 608 return ERROR_INVALID_OPERATION; 609 } 610 611 if ( (audioData == null) || (offsetInShorts < 0 ) || (sizeInShorts < 0) 612 || (offsetInShorts + sizeInShorts > audioData.length)) { 613 return ERROR_BAD_VALUE; 614 } 615 616 return native_read_in_short_array(audioData, offsetInShorts, sizeInShorts); 617 } 618 619 620 /** 621 * Reads audio data from the audio hardware for recording into a direct buffer. If this buffer 622 * is not a direct buffer, this method will always return 0. 623 * Note that the value returned by {@link java.nio.Buffer#position()} on this buffer is 624 * unchanged after a call to this method. 625 * @param audioBuffer the direct buffer to which the recorded audio data is written. 626 * @param sizeInBytes the number of requested bytes. 627 * @return the number of bytes that were read or or {@link #ERROR_INVALID_OPERATION} 628 * if the object wasn't properly initialized, or {@link #ERROR_BAD_VALUE} if 629 * the parameters don't resolve to valid data and indexes. 630 * The number of bytes will not exceed sizeInBytes. 631 */ 632 public int read(ByteBuffer audioBuffer, int sizeInBytes) { 633 if (mState != STATE_INITIALIZED) { 634 return ERROR_INVALID_OPERATION; 635 } 636 637 if ( (audioBuffer == null) || (sizeInBytes < 0) ) { 638 return ERROR_BAD_VALUE; 639 } 640 641 return native_read_in_direct_buffer(audioBuffer, sizeInBytes); 642 } 643 644 645 //-------------------------------------------------------------------------- 646 // Initialization / configuration 647 //-------------------- 648 /** 649 * Sets the listener the AudioRecord notifies when a previously set marker is reached or 650 * for each periodic record head position update. 651 * @param listener 652 */ 653 public void setRecordPositionUpdateListener(OnRecordPositionUpdateListener listener) { 654 setRecordPositionUpdateListener(listener, null); 655 } 656 657 /** 658 * Sets the listener the AudioRecord notifies when a previously set marker is reached or 659 * for each periodic record head position update. 660 * Use this method to receive AudioRecord events in the Handler associated with another 661 * thread than the one in which you created the AudioTrack instance. 662 * @param listener 663 * @param handler the Handler that will receive the event notification messages. 664 */ 665 public void setRecordPositionUpdateListener(OnRecordPositionUpdateListener listener, 666 Handler handler) { 667 synchronized (mPositionListenerLock) { 668 669 mPositionListener = listener; 670 671 if (listener != null) { 672 if (handler != null) { 673 mEventHandler = new NativeEventHandler(this, handler.getLooper()); 674 } else { 675 // no given handler, use the looper the AudioRecord was created in 676 mEventHandler = new NativeEventHandler(this, mInitializationLooper); 677 } 678 } else { 679 mEventHandler = null; 680 } 681 } 682 683 } 684 685 686 /** 687 * Sets the marker position at which the listener is called, if set with 688 * {@link #setRecordPositionUpdateListener(OnRecordPositionUpdateListener)} or 689 * {@link #setRecordPositionUpdateListener(OnRecordPositionUpdateListener, Handler)}. 690 * @param markerInFrames marker position expressed in frames 691 * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE}, 692 * {@link #ERROR_INVALID_OPERATION} 693 */ 694 public int setNotificationMarkerPosition(int markerInFrames) { 695 return native_set_marker_pos(markerInFrames); 696 } 697 698 699 /** 700 * Sets the period at which the listener is called, if set with 701 * {@link #setRecordPositionUpdateListener(OnRecordPositionUpdateListener)} or 702 * {@link #setRecordPositionUpdateListener(OnRecordPositionUpdateListener, Handler)}. 703 * @param periodInFrames update period expressed in frames 704 * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_INVALID_OPERATION} 705 */ 706 public int setPositionNotificationPeriod(int periodInFrames) { 707 return native_set_pos_update_period(periodInFrames); 708 } 709 710 711 //--------------------------------------------------------- 712 // Interface definitions 713 //-------------------- 714 /** 715 * Interface definition for a callback to be invoked when an AudioRecord has 716 * reached a notification marker set by {@link AudioRecord#setNotificationMarkerPosition(int)} 717 * or for periodic updates on the progress of the record head, as set by 718 * {@link AudioRecord#setPositionNotificationPeriod(int)}. 719 */ 720 public interface OnRecordPositionUpdateListener { 721 /** 722 * Called on the listener to notify it that the previously set marker has been reached 723 * by the recording head. 724 */ 725 void onMarkerReached(AudioRecord recorder); 726 727 /** 728 * Called on the listener to periodically notify it that the record head has reached 729 * a multiple of the notification period. 730 */ 731 void onPeriodicNotification(AudioRecord recorder); 732 } 733 734 735 736 //--------------------------------------------------------- 737 // Inner classes 738 //-------------------- 739 740 /** 741 * Helper class to handle the forwarding of native events to the appropriate listener 742 * (potentially) handled in a different thread 743 */ 744 private class NativeEventHandler extends Handler { 745 746 private final AudioRecord mAudioRecord; 747 748 NativeEventHandler(AudioRecord recorder, Looper looper) { 749 super(looper); 750 mAudioRecord = recorder; 751 } 752 753 @Override 754 public void handleMessage(Message msg) { 755 OnRecordPositionUpdateListener listener = null; 756 synchronized (mPositionListenerLock) { 757 listener = mAudioRecord.mPositionListener; 758 } 759 760 switch (msg.what) { 761 case NATIVE_EVENT_MARKER: 762 if (listener != null) { 763 listener.onMarkerReached(mAudioRecord); 764 } 765 break; 766 case NATIVE_EVENT_NEW_POS: 767 if (listener != null) { 768 listener.onPeriodicNotification(mAudioRecord); 769 } 770 break; 771 default: 772 Log.e(TAG, "[ android.media.AudioRecord.NativeEventHandler ] " + 773 "Unknown event type: " + msg.what); 774 break; 775 } 776 } 777 }; 778 779 780 //--------------------------------------------------------- 781 // Java methods called from the native side 782 //-------------------- 783 @SuppressWarnings("unused") 784 private static void postEventFromNative(Object audiorecord_ref, 785 int what, int arg1, int arg2, Object obj) { 786 //logd("Event posted from the native side: event="+ what + " args="+ arg1+" "+arg2); 787 AudioRecord recorder = (AudioRecord)((WeakReference)audiorecord_ref).get(); 788 if (recorder == null) { 789 return; 790 } 791 792 if (recorder.mEventHandler != null) { 793 Message m = 794 recorder.mEventHandler.obtainMessage(what, arg1, arg2, obj); 795 recorder.mEventHandler.sendMessage(m); 796 } 797 798 } 799 800 801 //--------------------------------------------------------- 802 // Native methods called from the Java side 803 //-------------------- 804 805 private native final int native_setup(Object audiorecord_this, 806 int recordSource, int sampleRate, int nbChannels, int audioFormat, 807 int buffSizeInBytes, int[] sessionId); 808 809 private native final void native_finalize(); 810 811 private native final void native_release(); 812 813 private native final int native_start(int syncEvent, int sessionId); 814 815 private native final void native_stop(); 816 817 private native final int native_read_in_byte_array(byte[] audioData, 818 int offsetInBytes, int sizeInBytes); 819 820 private native final int native_read_in_short_array(short[] audioData, 821 int offsetInShorts, int sizeInShorts); 822 823 private native final int native_read_in_direct_buffer(Object jBuffer, int sizeInBytes); 824 825 private native final int native_set_marker_pos(int marker); 826 private native final int native_get_marker_pos(); 827 828 private native final int native_set_pos_update_period(int updatePeriod); 829 private native final int native_get_pos_update_period(); 830 831 static private native final int native_get_min_buff_size( 832 int sampleRateInHz, int channelCount, int audioFormat); 833 834 835 //--------------------------------------------------------- 836 // Utility methods 837 //------------------ 838 839 private static void logd(String msg) { 840 Log.d(TAG, "[ android.media.AudioRecord ] " + msg); 841 } 842 843 private static void loge(String msg) { 844 Log.e(TAG, "[ android.media.AudioRecord ] " + msg); 845 } 846 847} 848