AudioTrack.java revision 88bde0ce3799c47530ea42ae3665bfa12ae38d11
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; 22 23import android.os.Handler; 24import android.os.Looper; 25import android.os.Message; 26import android.media.AudioManager; 27import android.util.Log; 28 29 30/** 31 * The AudioTrack class manages and plays a single audio resource for Java applications. 32 * It allows to stream PCM audio buffers to the audio hardware for playback. This is 33 * achieved by "pushing" the data to the AudioTrack object using one of the 34 * {@link #write(byte[], int, int)} and {@link #write(short[], int, int)} methods. 35 * 36 * <p>An AudioTrack instance can operate under two modes: static or streaming.<br> 37 * In Streaming mode, the application writes a continuous stream of data to the AudioTrack, using 38 * one of the {@code write()} methods. These are blocking and return when the data has been 39 * transferred from the Java layer to the native layer and queued for playback. The streaming 40 * mode is most useful when playing blocks of audio data that for instance are: 41 * 42 * <ul> 43 * <li>too big to fit in memory because of the duration of the sound to play,</li> 44 * <li>too big to fit in memory because of the characteristics of the audio data 45 * (high sampling rate, bits per sample ...)</li> 46 * <li>received or generated while previously queued audio is playing.</li> 47 * </ul> 48 * 49 * The static mode is to be chosen when dealing with short sounds that fit in memory and 50 * that need to be played with the smallest latency possible. The static mode will 51 * therefore be preferred for UI and game sounds that are played often, and with the 52 * smallest overhead possible. 53 * 54 * <p>Upon creation, an AudioTrack object initializes its associated audio buffer. 55 * The size of this buffer, specified during the construction, determines how long an AudioTrack 56 * can play before running out of data.<br> 57 * For an AudioTrack using the static mode, this size is the maximum size of the sound that can 58 * be played from it.<br> 59 * For the streaming mode, data will be written to the hardware in chunks of 60 * sizes inferior to the total buffer size. 61 */ 62public class AudioTrack 63{ 64 //--------------------------------------------------------- 65 // Constants 66 //-------------------- 67 /** Minimum value for a channel volume */ 68 private static final float VOLUME_MIN = 0.0f; 69 /** Maximum value for a channel volume */ 70 private static final float VOLUME_MAX = 1.0f; 71 72 /** indicates AudioTrack state is stopped */ 73 public static final int PLAYSTATE_STOPPED = 1; // matches SL_PLAYSTATE_STOPPED 74 /** indicates AudioTrack state is paused */ 75 public static final int PLAYSTATE_PAUSED = 2; // matches SL_PLAYSTATE_PAUSED 76 /** indicates AudioTrack state is playing */ 77 public static final int PLAYSTATE_PLAYING = 3; // matches SL_PLAYSTATE_PLAYING 78 79 /** 80 * Creation mode where audio data is transferred from Java to the native layer 81 * only once before the audio starts playing. 82 */ 83 public static final int MODE_STATIC = 0; 84 /** 85 * Creation mode where audio data is streamed from Java to the native layer 86 * as the audio is playing. 87 */ 88 public static final int MODE_STREAM = 1; 89 90 /** 91 * State of an AudioTrack that was not successfully initialized upon creation. 92 */ 93 public static final int STATE_UNINITIALIZED = 0; 94 /** 95 * State of an AudioTrack that is ready to be used. 96 */ 97 public static final int STATE_INITIALIZED = 1; 98 /** 99 * State of a successfully initialized AudioTrack that uses static data, 100 * but that hasn't received that data yet. 101 */ 102 public static final int STATE_NO_STATIC_DATA = 2; 103 104 // Error codes: 105 // to keep in sync with frameworks/base/core/jni/android_media_AudioTrack.cpp 106 /** 107 * Denotes a successful operation. 108 */ 109 public static final int SUCCESS = 0; 110 /** 111 * Denotes a generic operation failure. 112 */ 113 public static final int ERROR = -1; 114 /** 115 * Denotes a failure due to the use of an invalid value. 116 */ 117 public static final int ERROR_BAD_VALUE = -2; 118 /** 119 * Denotes a failure due to the improper use of a method. 120 */ 121 public static final int ERROR_INVALID_OPERATION = -3; 122 123 private static final int ERROR_NATIVESETUP_AUDIOSYSTEM = -16; 124 private static final int ERROR_NATIVESETUP_INVALIDCHANNELMASK = -17; 125 private static final int ERROR_NATIVESETUP_INVALIDFORMAT = -18; 126 private static final int ERROR_NATIVESETUP_INVALIDSTREAMTYPE = -19; 127 private static final int ERROR_NATIVESETUP_NATIVEINITFAILED = -20; 128 129 // Events: 130 // to keep in sync with frameworks/base/include/media/AudioTrack.h 131 /** 132 * Event id denotes when playback head has reached a previously set marker. 133 */ 134 private static final int NATIVE_EVENT_MARKER = 3; 135 /** 136 * Event id denotes when previously set update period has elapsed during playback. 137 */ 138 private static final int NATIVE_EVENT_NEW_POS = 4; 139 140 private final static String TAG = "AudioTrack-Java"; 141 142 143 //-------------------------------------------------------------------------- 144 // Member variables 145 //-------------------- 146 /** 147 * Indicates the state of the AudioTrack instance. 148 */ 149 private int mState = STATE_UNINITIALIZED; 150 /** 151 * Indicates the play state of the AudioTrack instance. 152 */ 153 private int mPlayState = PLAYSTATE_STOPPED; 154 /** 155 * Lock to make sure mPlayState updates are reflecting the actual state of the object. 156 */ 157 private final Object mPlayStateLock = new Object(); 158 /** 159 * The listener the AudioTrack notifies when the playback position reaches a marker 160 * or for periodic updates during the progression of the playback head. 161 * @see #setPlaybackPositionUpdateListener(OnPlaybackPositionUpdateListener) 162 */ 163 private OnPlaybackPositionUpdateListener mPositionListener = null; 164 /** 165 * Lock to protect event listener updates against event notifications. 166 */ 167 private final Object mPositionListenerLock = new Object(); 168 /** 169 * Size of the native audio buffer. 170 */ 171 private int mNativeBufferSizeInBytes = 0; 172 /** 173 * Handler for marker events coming from the native code. 174 */ 175 private NativeEventHandlerDelegate mEventHandlerDelegate = null; 176 /** 177 * Looper associated with the thread that creates the AudioTrack instance. 178 */ 179 private Looper mInitializationLooper = null; 180 /** 181 * The audio data sampling rate in Hz. 182 */ 183 private int mSampleRate = 22050; 184 /** 185 * The number of audio output channels (1 is mono, 2 is stereo). 186 */ 187 private int mChannelCount = 1; 188 /** 189 * The audio channel mask. 190 */ 191 private int mChannels = AudioFormat.CHANNEL_OUT_MONO; 192 193 /** 194 * The type of the audio stream to play. See 195 * {@link AudioManager#STREAM_VOICE_CALL}, {@link AudioManager#STREAM_SYSTEM}, 196 * {@link AudioManager#STREAM_RING}, {@link AudioManager#STREAM_MUSIC} and 197 * {@link AudioManager#STREAM_ALARM} 198 */ 199 private int mStreamType = AudioManager.STREAM_MUSIC; 200 /** 201 * The way audio is consumed by the hardware, streaming or static. 202 */ 203 private int mDataLoadMode = MODE_STREAM; 204 /** 205 * The current audio channel configuration. 206 */ 207 private int mChannelConfiguration = AudioFormat.CHANNEL_OUT_MONO; 208 /** 209 * The encoding of the audio samples. 210 * @see AudioFormat#ENCODING_PCM_8BIT 211 * @see AudioFormat#ENCODING_PCM_16BIT 212 */ 213 private int mAudioFormat = AudioFormat.ENCODING_PCM_16BIT; 214 /** 215 * Audio session ID 216 */ 217 private int mSessionId = 0; 218 219 220 //-------------------------------- 221 // Used exclusively by native code 222 //-------------------- 223 /** 224 * Accessed by native methods: provides access to C++ AudioTrack object. 225 */ 226 @SuppressWarnings("unused") 227 private int mNativeTrackInJavaObj; 228 /** 229 * Accessed by native methods: provides access to the JNI data (i.e. resources used by 230 * the native AudioTrack object, but not stored in it). 231 */ 232 @SuppressWarnings("unused") 233 private int mJniData; 234 235 236 //-------------------------------------------------------------------------- 237 // Constructor, Finalize 238 //-------------------- 239 /** 240 * Class constructor. 241 * @param streamType the type of the audio stream. See 242 * {@link AudioManager#STREAM_VOICE_CALL}, {@link AudioManager#STREAM_SYSTEM}, 243 * {@link AudioManager#STREAM_RING}, {@link AudioManager#STREAM_MUSIC} and 244 * {@link AudioManager#STREAM_ALARM} 245 * @param sampleRateInHz the sample rate expressed in Hertz. Examples of rates are (but 246 * not limited to) 44100, 22050 and 11025. 247 * @param channelConfig describes the configuration of the audio channels. 248 * See {@link AudioFormat#CHANNEL_OUT_MONO} and 249 * {@link AudioFormat#CHANNEL_OUT_STEREO} 250 * @param audioFormat the format in which the audio data is represented. 251 * See {@link AudioFormat#ENCODING_PCM_16BIT} and 252 * {@link AudioFormat#ENCODING_PCM_8BIT} 253 * @param bufferSizeInBytes the total size (in bytes) of the buffer where audio data is read 254 * from for playback. If using the AudioTrack in streaming mode, you can write data into 255 * this buffer in smaller chunks than this size. If using the AudioTrack in static mode, 256 * this is the maximum size of the sound that will be played for this instance. 257 * See {@link #getMinBufferSize(int, int, int)} to determine the minimum required buffer size 258 * for the successful creation of an AudioTrack instance in streaming mode. Using values 259 * smaller than getMinBufferSize() will result in an initialization failure. 260 * @param mode streaming or static buffer. See {@link #MODE_STATIC} and {@link #MODE_STREAM} 261 * @throws java.lang.IllegalArgumentException 262 */ 263 public AudioTrack(int streamType, int sampleRateInHz, int channelConfig, int audioFormat, 264 int bufferSizeInBytes, int mode) 265 throws IllegalArgumentException { 266 this(streamType, sampleRateInHz, channelConfig, audioFormat, 267 bufferSizeInBytes, mode, 0); 268 } 269 270 /** 271 * Class constructor with audio session. Use this constructor when the AudioTrack must be 272 * attached to a particular audio session. The primary use of the audio session ID is to 273 * associate audio effects to a particular instance of AudioTrack: if an audio session ID 274 * is provided when creating an AudioEffect, this effect will be applied only to audio tracks 275 * and media players in the same session and not to the output mix. 276 * When an AudioTrack is created without specifying a session, it will create its own session 277 * which can be retreived by calling the {@link #getAudioSessionId()} method. 278 * If a session ID is provided, this AudioTrack will share effects attached to this session 279 * with all other media players or audio tracks in the same session. 280 * @param streamType the type of the audio stream. See 281 * {@link AudioManager#STREAM_VOICE_CALL}, {@link AudioManager#STREAM_SYSTEM}, 282 * {@link AudioManager#STREAM_RING}, {@link AudioManager#STREAM_MUSIC} and 283 * {@link AudioManager#STREAM_ALARM} 284 * @param sampleRateInHz the sample rate expressed in Hertz. Examples of rates are (but 285 * not limited to) 44100, 22050 and 11025. 286 * @param channelConfig describes the configuration of the audio channels. 287 * See {@link AudioFormat#CHANNEL_OUT_MONO} and 288 * {@link AudioFormat#CHANNEL_OUT_STEREO} 289 * @param audioFormat the format in which the audio data is represented. 290 * See {@link AudioFormat#ENCODING_PCM_16BIT} and 291 * {@link AudioFormat#ENCODING_PCM_8BIT} 292 * @param bufferSizeInBytes the total size (in bytes) of the buffer where audio data is read 293 * from for playback. If using the AudioTrack in streaming mode, you can write data into 294 * this buffer in smaller chunks than this size. If using the AudioTrack in static mode, 295 * this is the maximum size of the sound that will be played for this instance. 296 * See {@link #getMinBufferSize(int, int, int)} to determine the minimum required buffer size 297 * for the successful creation of an AudioTrack instance in streaming mode. Using values 298 * smaller than getMinBufferSize() will result in an initialization failure. 299 * @param mode streaming or static buffer. See {@link #MODE_STATIC} and {@link #MODE_STREAM} 300 * @param sessionId Id of audio session the AudioTrack must be attached to 301 * @throws java.lang.IllegalArgumentException 302 */ 303 public AudioTrack(int streamType, int sampleRateInHz, int channelConfig, int audioFormat, 304 int bufferSizeInBytes, int mode, int sessionId) 305 throws IllegalArgumentException { 306 mState = STATE_UNINITIALIZED; 307 308 // remember which looper is associated with the AudioTrack instanciation 309 if ((mInitializationLooper = Looper.myLooper()) == null) { 310 mInitializationLooper = Looper.getMainLooper(); 311 } 312 313 audioParamCheck(streamType, sampleRateInHz, channelConfig, audioFormat, mode); 314 315 audioBuffSizeCheck(bufferSizeInBytes); 316 317 if (sessionId < 0) { 318 throw (new IllegalArgumentException("Invalid audio session ID: "+sessionId)); 319 } 320 321 int[] session = new int[1]; 322 session[0] = sessionId; 323 // native initialization 324 int initResult = native_setup(new WeakReference<AudioTrack>(this), 325 mStreamType, mSampleRate, mChannels, mAudioFormat, 326 mNativeBufferSizeInBytes, mDataLoadMode, session); 327 if (initResult != SUCCESS) { 328 loge("Error code "+initResult+" when initializing AudioTrack."); 329 return; // with mState == STATE_UNINITIALIZED 330 } 331 332 mSessionId = session[0]; 333 334 if (mDataLoadMode == MODE_STATIC) { 335 mState = STATE_NO_STATIC_DATA; 336 } else { 337 mState = STATE_INITIALIZED; 338 } 339 } 340 341 342 // Convenience method for the constructor's parameter checks. 343 // This is where constructor IllegalArgumentException-s are thrown 344 // postconditions: 345 // mStreamType is valid 346 // mChannelCount is valid 347 // mChannels is valid 348 // mAudioFormat is valid 349 // mSampleRate is valid 350 // mDataLoadMode is valid 351 private void audioParamCheck(int streamType, int sampleRateInHz, 352 int channelConfig, int audioFormat, int mode) { 353 354 //-------------- 355 // stream type 356 if( (streamType != AudioManager.STREAM_ALARM) && (streamType != AudioManager.STREAM_MUSIC) 357 && (streamType != AudioManager.STREAM_RING) && (streamType != AudioManager.STREAM_SYSTEM) 358 && (streamType != AudioManager.STREAM_VOICE_CALL) 359 && (streamType != AudioManager.STREAM_NOTIFICATION) 360 && (streamType != AudioManager.STREAM_BLUETOOTH_SCO) 361 && (streamType != AudioManager.STREAM_DTMF)) { 362 throw (new IllegalArgumentException("Invalid stream type.")); 363 } else { 364 mStreamType = streamType; 365 } 366 367 //-------------- 368 // sample rate 369 if ( (sampleRateInHz < 4000) || (sampleRateInHz > 48000) ) { 370 throw (new IllegalArgumentException(sampleRateInHz 371 + "Hz is not a supported sample rate.")); 372 } else { 373 mSampleRate = sampleRateInHz; 374 } 375 376 //-------------- 377 // channel config 378 mChannelConfiguration = channelConfig; 379 380 switch (channelConfig) { 381 case AudioFormat.CHANNEL_OUT_DEFAULT: //AudioFormat.CHANNEL_CONFIGURATION_DEFAULT 382 case AudioFormat.CHANNEL_OUT_MONO: 383 case AudioFormat.CHANNEL_CONFIGURATION_MONO: 384 mChannelCount = 1; 385 mChannels = AudioFormat.CHANNEL_OUT_MONO; 386 break; 387 case AudioFormat.CHANNEL_OUT_STEREO: 388 case AudioFormat.CHANNEL_CONFIGURATION_STEREO: 389 mChannelCount = 2; 390 mChannels = AudioFormat.CHANNEL_OUT_STEREO; 391 break; 392 default: 393 mChannelCount = 0; 394 mChannels = AudioFormat.CHANNEL_INVALID; 395 mChannelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_INVALID; 396 throw(new IllegalArgumentException("Unsupported channel configuration.")); 397 } 398 399 //-------------- 400 // audio format 401 switch (audioFormat) { 402 case AudioFormat.ENCODING_DEFAULT: 403 mAudioFormat = AudioFormat.ENCODING_PCM_16BIT; 404 break; 405 case AudioFormat.ENCODING_PCM_16BIT: 406 case AudioFormat.ENCODING_PCM_8BIT: 407 mAudioFormat = audioFormat; 408 break; 409 default: 410 mAudioFormat = AudioFormat.ENCODING_INVALID; 411 throw(new IllegalArgumentException("Unsupported sample encoding." 412 + " Should be ENCODING_PCM_8BIT or ENCODING_PCM_16BIT.")); 413 } 414 415 //-------------- 416 // audio load mode 417 if ( (mode != MODE_STREAM) && (mode != MODE_STATIC) ) { 418 throw(new IllegalArgumentException("Invalid mode.")); 419 } else { 420 mDataLoadMode = mode; 421 } 422 } 423 424 425 // Convenience method for the contructor's audio buffer size check. 426 // preconditions: 427 // mChannelCount is valid 428 // mAudioFormat is valid 429 // postcondition: 430 // mNativeBufferSizeInBytes is valid (multiple of frame size, positive) 431 private void audioBuffSizeCheck(int audioBufferSize) { 432 // NB: this section is only valid with PCM data. 433 // To update when supporting compressed formats 434 int frameSizeInBytes = mChannelCount 435 * (mAudioFormat == AudioFormat.ENCODING_PCM_8BIT ? 1 : 2); 436 if ((audioBufferSize % frameSizeInBytes != 0) || (audioBufferSize < 1)) { 437 throw (new IllegalArgumentException("Invalid audio buffer size.")); 438 } 439 440 mNativeBufferSizeInBytes = audioBufferSize; 441 } 442 443 444 /** 445 * Releases the native AudioTrack resources. 446 */ 447 public void release() { 448 // even though native_release() stops the native AudioTrack, we need to stop 449 // AudioTrack subclasses too. 450 try { 451 stop(); 452 } catch(IllegalStateException ise) { 453 // don't raise an exception, we're releasing the resources. 454 } 455 native_release(); 456 mState = STATE_UNINITIALIZED; 457 } 458 459 @Override 460 protected void finalize() { 461 native_finalize(); 462 } 463 464 //-------------------------------------------------------------------------- 465 // Getters 466 //-------------------- 467 /** 468 * Returns the minimum valid volume value. Volume values set under this one will 469 * be clamped at this value. 470 * @return the minimum volume expressed as a linear attenuation. 471 */ 472 static public float getMinVolume() { 473 return AudioTrack.VOLUME_MIN; 474 } 475 476 /** 477 * Returns the maximum valid volume value. Volume values set above this one will 478 * be clamped at this value. 479 * @return the maximum volume expressed as a linear attenuation. 480 */ 481 static public float getMaxVolume() { 482 return AudioTrack.VOLUME_MAX; 483 } 484 485 /** 486 * Returns the configured audio data sample rate in Hz 487 */ 488 public int getSampleRate() { 489 return mSampleRate; 490 } 491 492 /** 493 * Returns the current playback rate in Hz. 494 */ 495 public int getPlaybackRate() { 496 return native_get_playback_rate(); 497 } 498 499 /** 500 * Returns the configured audio data format. See {@link AudioFormat#ENCODING_PCM_16BIT} 501 * and {@link AudioFormat#ENCODING_PCM_8BIT}. 502 */ 503 public int getAudioFormat() { 504 return mAudioFormat; 505 } 506 507 /** 508 * Returns the type of audio stream this AudioTrack is configured for. 509 * Compare the result against {@link AudioManager#STREAM_VOICE_CALL}, 510 * {@link AudioManager#STREAM_SYSTEM}, {@link AudioManager#STREAM_RING}, 511 * {@link AudioManager#STREAM_MUSIC} or {@link AudioManager#STREAM_ALARM} 512 */ 513 public int getStreamType() { 514 return mStreamType; 515 } 516 517 /** 518 * Returns the configured channel configuration. 519 520 * See {@link AudioFormat#CHANNEL_OUT_MONO} 521 * and {@link AudioFormat#CHANNEL_OUT_STEREO}. 522 */ 523 public int getChannelConfiguration() { 524 return mChannelConfiguration; 525 } 526 527 /** 528 * Returns the configured number of channels. 529 */ 530 public int getChannelCount() { 531 return mChannelCount; 532 } 533 534 /** 535 * Returns the state of the AudioTrack instance. This is useful after the 536 * AudioTrack instance has been created to check if it was initialized 537 * properly. This ensures that the appropriate hardware resources have been 538 * acquired. 539 * @see #STATE_INITIALIZED 540 * @see #STATE_NO_STATIC_DATA 541 * @see #STATE_UNINITIALIZED 542 */ 543 public int getState() { 544 return mState; 545 } 546 547 /** 548 * Returns the playback state of the AudioTrack instance. 549 * @see #PLAYSTATE_STOPPED 550 * @see #PLAYSTATE_PAUSED 551 * @see #PLAYSTATE_PLAYING 552 */ 553 public int getPlayState() { 554 return mPlayState; 555 } 556 557 /** 558 * Returns the native frame count used by the hardware. 559 */ 560 protected int getNativeFrameCount() { 561 return native_get_native_frame_count(); 562 } 563 564 /** 565 * Returns marker position expressed in frames. 566 */ 567 public int getNotificationMarkerPosition() { 568 return native_get_marker_pos(); 569 } 570 571 /** 572 * Returns the notification update period expressed in frames. 573 */ 574 public int getPositionNotificationPeriod() { 575 return native_get_pos_update_period(); 576 } 577 578 /** 579 * Returns the playback head position expressed in frames 580 */ 581 public int getPlaybackHeadPosition() { 582 return native_get_position(); 583 } 584 585 /** 586 * Returns the hardware output sample rate 587 */ 588 static public int getNativeOutputSampleRate(int streamType) { 589 return native_get_output_sample_rate(streamType); 590 } 591 592 /** 593 * Returns the minimum buffer size required for the successful creation of an AudioTrack 594 * object to be created in the {@link #MODE_STREAM} mode. Note that this size doesn't 595 * guarantee a smooth playback under load, and higher values should be chosen according to 596 * the expected frequency at which the buffer will be refilled with additional data to play. 597 * @param sampleRateInHz the sample rate expressed in Hertz. 598 * @param channelConfig describes the configuration of the audio channels. 599 * See {@link AudioFormat#CHANNEL_OUT_MONO} and 600 * {@link AudioFormat#CHANNEL_OUT_STEREO} 601 * @param audioFormat the format in which the audio data is represented. 602 * See {@link AudioFormat#ENCODING_PCM_16BIT} and 603 * {@link AudioFormat#ENCODING_PCM_8BIT} 604 * @return {@link #ERROR_BAD_VALUE} if an invalid parameter was passed, 605 * or {@link #ERROR} if the implementation was unable to query the hardware for its output 606 * properties, 607 * or the minimum buffer size expressed in bytes. 608 */ 609 static public int getMinBufferSize(int sampleRateInHz, int channelConfig, int audioFormat) { 610 int channelCount = 0; 611 switch(channelConfig) { 612 case AudioFormat.CHANNEL_OUT_MONO: 613 case AudioFormat.CHANNEL_CONFIGURATION_MONO: 614 channelCount = 1; 615 break; 616 case AudioFormat.CHANNEL_OUT_STEREO: 617 case AudioFormat.CHANNEL_CONFIGURATION_STEREO: 618 channelCount = 2; 619 break; 620 default: 621 loge("getMinBufferSize(): Invalid channel configuration."); 622 return AudioTrack.ERROR_BAD_VALUE; 623 } 624 625 if ((audioFormat != AudioFormat.ENCODING_PCM_16BIT) 626 && (audioFormat != AudioFormat.ENCODING_PCM_8BIT)) { 627 loge("getMinBufferSize(): Invalid audio format."); 628 return AudioTrack.ERROR_BAD_VALUE; 629 } 630 631 if ( (sampleRateInHz < 4000) || (sampleRateInHz > 48000) ) { 632 loge("getMinBufferSize(): " + sampleRateInHz +"Hz is not a supported sample rate."); 633 return AudioTrack.ERROR_BAD_VALUE; 634 } 635 636 int size = native_get_min_buff_size(sampleRateInHz, channelCount, audioFormat); 637 if ((size == -1) || (size == 0)) { 638 loge("getMinBufferSize(): error querying hardware"); 639 return AudioTrack.ERROR; 640 } 641 else { 642 return size; 643 } 644 } 645 646 /** 647 * Returns the audio session ID. 648 * 649 * @return the ID of the audio session this AudioTrack belongs to. 650 */ 651 public int getAudioSessionId() { 652 return mSessionId; 653 } 654 655 //-------------------------------------------------------------------------- 656 // Initialization / configuration 657 //-------------------- 658 /** 659 * Sets the listener the AudioTrack notifies when a previously set marker is reached or 660 * for each periodic playback head position update. 661 * Notifications will be received in the same thread as the one in which the AudioTrack 662 * instance was created. 663 * @param listener 664 */ 665 public void setPlaybackPositionUpdateListener(OnPlaybackPositionUpdateListener listener) { 666 setPlaybackPositionUpdateListener(listener, null); 667 } 668 669 /** 670 * Sets the listener the AudioTrack notifies when a previously set marker is reached or 671 * for each periodic playback head position update. 672 * Use this method to receive AudioTrack events in the Handler associated with another 673 * thread than the one in which you created the AudioTrack instance. 674 * @param listener 675 * @param handler the Handler that will receive the event notification messages. 676 */ 677 public void setPlaybackPositionUpdateListener(OnPlaybackPositionUpdateListener listener, 678 Handler handler) { 679 synchronized (mPositionListenerLock) { 680 mPositionListener = listener; 681 } 682 if (listener != null) { 683 mEventHandlerDelegate = new NativeEventHandlerDelegate(this, handler); 684 } 685 686 } 687 688 689 690 /** 691 * Sets the specified left/right output volume values on the AudioTrack. Values are clamped 692 * to the ({@link #getMinVolume()}, {@link #getMaxVolume()}) interval if outside this range. 693 * @param leftVolume output attenuation for the left channel. A value of 0.0f is silence, 694 * a value of 1.0f is no attenuation. 695 * @param rightVolume output attenuation for the right channel 696 * @return error code or success, see {@link #SUCCESS}, 697 * {@link #ERROR_INVALID_OPERATION} 698 */ 699 public int setStereoVolume(float leftVolume, float rightVolume) { 700 if (mState != STATE_INITIALIZED) { 701 return ERROR_INVALID_OPERATION; 702 } 703 704 // clamp the volumes 705 if (leftVolume < getMinVolume()) { 706 leftVolume = getMinVolume(); 707 } 708 if (leftVolume > getMaxVolume()) { 709 leftVolume = getMaxVolume(); 710 } 711 if (rightVolume < getMinVolume()) { 712 rightVolume = getMinVolume(); 713 } 714 if (rightVolume > getMaxVolume()) { 715 rightVolume = getMaxVolume(); 716 } 717 718 native_setVolume(leftVolume, rightVolume); 719 720 return SUCCESS; 721 } 722 723 724 /** 725 * Sets the playback sample rate for this track. This sets the sampling rate at which 726 * the audio data will be consumed and played back, not the original sampling rate of the 727 * content. Setting it to half the sample rate of the content will cause the playback to 728 * last twice as long, but will also result in a negative pitch shift. 729 * The valid sample rate range if from 1Hz to twice the value returned by 730 * {@link #getNativeOutputSampleRate(int)}. 731 * @param sampleRateInHz the sample rate expressed in Hz 732 * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE}, 733 * {@link #ERROR_INVALID_OPERATION} 734 */ 735 public int setPlaybackRate(int sampleRateInHz) { 736 if (mState != STATE_INITIALIZED) { 737 return ERROR_INVALID_OPERATION; 738 } 739 if (sampleRateInHz <= 0) { 740 return ERROR_BAD_VALUE; 741 } 742 return native_set_playback_rate(sampleRateInHz); 743 } 744 745 746 /** 747 * Sets the position of the notification marker. 748 * @param markerInFrames marker in frames 749 * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE}, 750 * {@link #ERROR_INVALID_OPERATION} 751 */ 752 public int setNotificationMarkerPosition(int markerInFrames) { 753 if (mState != STATE_INITIALIZED) { 754 return ERROR_INVALID_OPERATION; 755 } 756 return native_set_marker_pos(markerInFrames); 757 } 758 759 760 /** 761 * Sets the period for the periodic notification event. 762 * @param periodInFrames update period expressed in frames 763 * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_INVALID_OPERATION} 764 */ 765 public int setPositionNotificationPeriod(int periodInFrames) { 766 if (mState != STATE_INITIALIZED) { 767 return ERROR_INVALID_OPERATION; 768 } 769 return native_set_pos_update_period(periodInFrames); 770 } 771 772 773 /** 774 * Sets the playback head position. The track must be stopped for the position to be changed. 775 * @param positionInFrames playback head position expressed in frames 776 * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE}, 777 * {@link #ERROR_INVALID_OPERATION} 778 */ 779 public int setPlaybackHeadPosition(int positionInFrames) { 780 synchronized(mPlayStateLock) { 781 if ((mPlayState == PLAYSTATE_STOPPED) || (mPlayState == PLAYSTATE_PAUSED)) { 782 return native_set_position(positionInFrames); 783 } else { 784 return ERROR_INVALID_OPERATION; 785 } 786 } 787 } 788 789 /** 790 * Sets the loop points and the loop count. The loop can be infinite. 791 * @param startInFrames loop start marker expressed in frames 792 * @param endInFrames loop end marker expressed in frames 793 * @param loopCount the number of times the loop is looped. 794 * A value of -1 means infinite looping. 795 * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE}, 796 * {@link #ERROR_INVALID_OPERATION} 797 */ 798 public int setLoopPoints(int startInFrames, int endInFrames, int loopCount) { 799 if (mDataLoadMode == MODE_STREAM) { 800 return ERROR_INVALID_OPERATION; 801 } 802 return native_set_loop(startInFrames, endInFrames, loopCount); 803 } 804 805 /** 806 * Sets the initialization state of the instance. To be used in an AudioTrack subclass 807 * constructor to set a subclass-specific post-initialization state. 808 * @param state the state of the AudioTrack instance 809 */ 810 protected void setState(int state) { 811 mState = state; 812 } 813 814 815 //--------------------------------------------------------- 816 // Transport control methods 817 //-------------------- 818 /** 819 * Starts playing an AudioTrack. 820 * 821 * @throws IllegalStateException 822 */ 823 public void play() 824 throws IllegalStateException { 825 if (mState != STATE_INITIALIZED) { 826 throw(new IllegalStateException("play() called on uninitialized AudioTrack.")); 827 } 828 829 synchronized(mPlayStateLock) { 830 native_start(); 831 mPlayState = PLAYSTATE_PLAYING; 832 } 833 } 834 835 /** 836 * Stops playing the audio data. 837 * 838 * @throws IllegalStateException 839 */ 840 public void stop() 841 throws IllegalStateException { 842 if (mState != STATE_INITIALIZED) { 843 throw(new IllegalStateException("stop() called on uninitialized AudioTrack.")); 844 } 845 846 // stop playing 847 synchronized(mPlayStateLock) { 848 native_stop(); 849 mPlayState = PLAYSTATE_STOPPED; 850 } 851 } 852 853 /** 854 * Pauses the playback of the audio data. Data that has not been played 855 * back will not be discarded. Subsequent calls to {@link #play} will play 856 * this data back. 857 * 858 * @throws IllegalStateException 859 */ 860 public void pause() 861 throws IllegalStateException { 862 if (mState != STATE_INITIALIZED) { 863 throw(new IllegalStateException("pause() called on uninitialized AudioTrack.")); 864 } 865 //logd("pause()"); 866 867 // pause playback 868 synchronized(mPlayStateLock) { 869 native_pause(); 870 mPlayState = PLAYSTATE_PAUSED; 871 } 872 } 873 874 875 //--------------------------------------------------------- 876 // Audio data supply 877 //-------------------- 878 879 /** 880 * Flushes the audio data currently queued for playback. Any data that has 881 * not been played back will be discarded. 882 */ 883 public void flush() { 884 if (mState == STATE_INITIALIZED) { 885 // flush the data in native layer 886 native_flush(); 887 } 888 889 } 890 891 /** 892 * Writes the audio data to the audio hardware for playback. Will block until 893 * all data has been written to the audio mixer. 894 * Note that the actual playback of this data might occur after this function 895 * returns. This function is thread safe with respect to {@link #stop} calls, 896 * in which case all of the specified data might not be written to the mixer. 897 * 898 * @param audioData the array that holds the data to play. 899 * @param offsetInBytes the offset expressed in bytes in audioData where the data to play 900 * starts. 901 * @param sizeInBytes the number of bytes to read in audioData after the offset. 902 * @return the number of bytes that were written or {@link #ERROR_INVALID_OPERATION} 903 * if the object wasn't properly initialized, or {@link #ERROR_BAD_VALUE} if 904 * the parameters don't resolve to valid data and indexes. 905 */ 906 907 public int write(byte[] audioData,int offsetInBytes, int sizeInBytes) { 908 if ((mDataLoadMode == MODE_STATIC) 909 && (mState == STATE_NO_STATIC_DATA) 910 && (sizeInBytes > 0)) { 911 mState = STATE_INITIALIZED; 912 } 913 914 if (mState != STATE_INITIALIZED) { 915 return ERROR_INVALID_OPERATION; 916 } 917 918 if ( (audioData == null) || (offsetInBytes < 0 ) || (sizeInBytes < 0) 919 || (offsetInBytes + sizeInBytes > audioData.length)) { 920 return ERROR_BAD_VALUE; 921 } 922 923 return native_write_byte(audioData, offsetInBytes, sizeInBytes, mAudioFormat); 924 } 925 926 927 /** 928 * Writes the audio data to the audio hardware for playback. Will block until 929 * all data has been written to the audio mixer. 930 * Note that the actual playback of this data might occur after this function 931 * returns. This function is thread safe with respect to {@link #stop} calls, 932 * in which case all of the specified data might not be written to the mixer. 933 * 934 * @param audioData the array that holds the data to play. 935 * @param offsetInShorts the offset expressed in shorts in audioData where the data to play 936 * starts. 937 * @param sizeInShorts the number of bytes to read in audioData after the offset. 938 * @return the number of shorts that were written or {@link #ERROR_INVALID_OPERATION} 939 * if the object wasn't properly initialized, or {@link #ERROR_BAD_VALUE} if 940 * the parameters don't resolve to valid data and indexes. 941 */ 942 943 public int write(short[] audioData, int offsetInShorts, int sizeInShorts) { 944 if ((mDataLoadMode == MODE_STATIC) 945 && (mState == STATE_NO_STATIC_DATA) 946 && (sizeInShorts > 0)) { 947 mState = STATE_INITIALIZED; 948 } 949 950 if (mState != STATE_INITIALIZED) { 951 return ERROR_INVALID_OPERATION; 952 } 953 954 if ( (audioData == null) || (offsetInShorts < 0 ) || (sizeInShorts < 0) 955 || (offsetInShorts + sizeInShorts > audioData.length)) { 956 return ERROR_BAD_VALUE; 957 } 958 959 return native_write_short(audioData, offsetInShorts, sizeInShorts, mAudioFormat); 960 } 961 962 963 /** 964 * Notifies the native resource to reuse the audio data already loaded in the native 965 * layer. This call is only valid with AudioTrack instances that don't use the streaming 966 * model. 967 * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE}, 968 * {@link #ERROR_INVALID_OPERATION} 969 */ 970 public int reloadStaticData() { 971 if (mDataLoadMode == MODE_STREAM) { 972 return ERROR_INVALID_OPERATION; 973 } 974 return native_reload_static(); 975 } 976 977 //-------------------------------------------------------------------------- 978 // Audio effects management 979 //-------------------- 980 981 /** 982 * Attaches an auxiliary effect to the audio track. A typical auxiliary 983 * effect is a reverberation effect which can be applied on any sound source 984 * that directs a certain amount of its energy to this effect. This amount 985 * is defined by setAuxEffectSendLevel(). 986 * {@see #setAuxEffectSendLevel(float)}. 987 * <p>After creating an auxiliary effect (e.g. 988 * {@link android.media.audiofx.EnvironmentalReverb}), retrieve its ID with 989 * {@link android.media.audiofx.AudioEffect#getId()} and use it when calling 990 * this method to attach the audio track to the effect. 991 * <p>To detach the effect from the audio track, call this method with a 992 * null effect id. 993 * 994 * @param effectId system wide unique id of the effect to attach 995 * @return error code or success, see {@link #SUCCESS}, 996 * {@link #ERROR_INVALID_OPERATION}, {@link #ERROR_BAD_VALUE} 997 */ 998 public int attachAuxEffect(int effectId) { 999 if (mState != STATE_INITIALIZED) { 1000 return ERROR_INVALID_OPERATION; 1001 } 1002 return native_attachAuxEffect(effectId); 1003 } 1004 1005 /** 1006 * Sets the send level of the audio track to the attached auxiliary effect 1007 * {@link #attachAuxEffect(int)}. The level value range is 0 to 1.0. 1008 * <p>By default the send level is 0, so even if an effect is attached to the player 1009 * this method must be called for the effect to be applied. 1010 * <p>Note that the passed level value is a raw scalar. UI controls should be scaled 1011 * logarithmically: the gain applied by audio framework ranges from -72dB to 0dB, 1012 * so an appropriate conversion from linear UI input x to level is: 1013 * x == 0 -> level = 0 1014 * 0 < x <= R -> level = 10^(72*(x-R)/20/R) 1015 * 1016 * @param level send level scalar 1017 * @return error code or success, see {@link #SUCCESS}, 1018 * {@link #ERROR_INVALID_OPERATION} 1019 */ 1020 public int setAuxEffectSendLevel(float level) { 1021 if (mState != STATE_INITIALIZED) { 1022 return ERROR_INVALID_OPERATION; 1023 } 1024 // clamp the level 1025 if (level < getMinVolume()) { 1026 level = getMinVolume(); 1027 } 1028 if (level > getMaxVolume()) { 1029 level = getMaxVolume(); 1030 } 1031 native_setAuxEffectSendLevel(level); 1032 return SUCCESS; 1033 } 1034 1035 //--------------------------------------------------------- 1036 // Interface definitions 1037 //-------------------- 1038 /** 1039 * Interface definition for a callback to be invoked when the playback head position of 1040 * an AudioTrack has reached a notification marker or has increased by a certain period. 1041 */ 1042 public interface OnPlaybackPositionUpdateListener { 1043 /** 1044 * Called on the listener to notify it that the previously set marker has been reached 1045 * by the playback head. 1046 */ 1047 void onMarkerReached(AudioTrack track); 1048 1049 /** 1050 * Called on the listener to periodically notify it that the playback head has reached 1051 * a multiple of the notification period. 1052 */ 1053 void onPeriodicNotification(AudioTrack track); 1054 } 1055 1056 1057 //--------------------------------------------------------- 1058 // Inner classes 1059 //-------------------- 1060 /** 1061 * Helper class to handle the forwarding of native events to the appropriate listener 1062 * (potentially) handled in a different thread 1063 */ 1064 private class NativeEventHandlerDelegate { 1065 private final AudioTrack mAudioTrack; 1066 private final Handler mHandler; 1067 1068 NativeEventHandlerDelegate(AudioTrack track, Handler handler) { 1069 mAudioTrack = track; 1070 // find the looper for our new event handler 1071 Looper looper; 1072 if (handler != null) { 1073 looper = handler.getLooper(); 1074 } else { 1075 // no given handler, use the looper the AudioTrack was created in 1076 looper = mInitializationLooper; 1077 } 1078 1079 // construct the event handler with this looper 1080 if (looper != null) { 1081 // implement the event handler delegate 1082 mHandler = new Handler(looper) { 1083 @Override 1084 public void handleMessage(Message msg) { 1085 if (mAudioTrack == null) { 1086 return; 1087 } 1088 OnPlaybackPositionUpdateListener listener = null; 1089 synchronized (mPositionListenerLock) { 1090 listener = mAudioTrack.mPositionListener; 1091 } 1092 switch(msg.what) { 1093 case NATIVE_EVENT_MARKER: 1094 if (listener != null) { 1095 listener.onMarkerReached(mAudioTrack); 1096 } 1097 break; 1098 case NATIVE_EVENT_NEW_POS: 1099 if (listener != null) { 1100 listener.onPeriodicNotification(mAudioTrack); 1101 } 1102 break; 1103 default: 1104 Log.e(TAG, "[ android.media.AudioTrack.NativeEventHandler ] " + 1105 "Unknown event type: " + msg.what); 1106 break; 1107 } 1108 } 1109 }; 1110 } else { 1111 mHandler = null; 1112 } 1113 } 1114 1115 Handler getHandler() { 1116 return mHandler; 1117 } 1118 } 1119 1120 1121 //--------------------------------------------------------- 1122 // Java methods called from the native side 1123 //-------------------- 1124 @SuppressWarnings("unused") 1125 private static void postEventFromNative(Object audiotrack_ref, 1126 int what, int arg1, int arg2, Object obj) { 1127 //logd("Event posted from the native side: event="+ what + " args="+ arg1+" "+arg2); 1128 AudioTrack track = (AudioTrack)((WeakReference)audiotrack_ref).get(); 1129 if (track == null) { 1130 return; 1131 } 1132 1133 if (track.mEventHandlerDelegate != null) { 1134 Message m = 1135 track.mEventHandlerDelegate.getHandler().obtainMessage(what, arg1, arg2, obj); 1136 track.mEventHandlerDelegate.getHandler().sendMessage(m); 1137 } 1138 1139 } 1140 1141 1142 //--------------------------------------------------------- 1143 // Native methods called from the Java side 1144 //-------------------- 1145 1146 private native final int native_setup(Object audiotrack_this, 1147 int streamType, int sampleRate, int nbChannels, int audioFormat, 1148 int buffSizeInBytes, int mode, int[] sessionId); 1149 1150 private native final void native_finalize(); 1151 1152 private native final void native_release(); 1153 1154 private native final void native_start(); 1155 1156 private native final void native_stop(); 1157 1158 private native final void native_pause(); 1159 1160 private native final void native_flush(); 1161 1162 private native final int native_write_byte(byte[] audioData, 1163 int offsetInBytes, int sizeInBytes, int format); 1164 1165 private native final int native_write_short(short[] audioData, 1166 int offsetInShorts, int sizeInShorts, int format); 1167 1168 private native final int native_reload_static(); 1169 1170 private native final int native_get_native_frame_count(); 1171 1172 private native final void native_setVolume(float leftVolume, float rightVolume); 1173 1174 private native final int native_set_playback_rate(int sampleRateInHz); 1175 private native final int native_get_playback_rate(); 1176 1177 private native final int native_set_marker_pos(int marker); 1178 private native final int native_get_marker_pos(); 1179 1180 private native final int native_set_pos_update_period(int updatePeriod); 1181 private native final int native_get_pos_update_period(); 1182 1183 private native final int native_set_position(int position); 1184 private native final int native_get_position(); 1185 1186 private native final int native_set_loop(int start, int end, int loopCount); 1187 1188 static private native final int native_get_output_sample_rate(int streamType); 1189 static private native final int native_get_min_buff_size( 1190 int sampleRateInHz, int channelConfig, int audioFormat); 1191 1192 private native final int native_get_session_id(); 1193 1194 private native final int native_attachAuxEffect(int effectId); 1195 private native final void native_setAuxEffectSendLevel(float level); 1196 1197 //--------------------------------------------------------- 1198 // Utility methods 1199 //------------------ 1200 1201 private static void logd(String msg) { 1202 Log.d(TAG, "[ android.media.AudioTrack ] " + msg); 1203 } 1204 1205 private static void loge(String msg) { 1206 Log.e(TAG, "[ android.media.AudioTrack ] " + msg); 1207 } 1208 1209} 1210