AudioTrack.java revision 806114bc6f5a87b35735d229e1c223bc37613ec7
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.annotation.Retention; 20import java.lang.annotation.RetentionPolicy; 21import java.lang.ref.WeakReference; 22import java.nio.ByteBuffer; 23import java.nio.NioUtils; 24import java.util.Iterator; 25import java.util.Set; 26 27import android.annotation.IntDef; 28import android.app.ActivityThread; 29import android.app.AppOpsManager; 30import android.content.Context; 31import android.os.Handler; 32import android.os.IBinder; 33import android.os.Looper; 34import android.os.Message; 35import android.os.Process; 36import android.os.RemoteException; 37import android.os.ServiceManager; 38import android.util.Log; 39 40import com.android.internal.app.IAppOpsService; 41 42 43/** 44 * The AudioTrack class manages and plays a single audio resource for Java applications. 45 * It allows streaming of PCM audio buffers to the audio sink for playback. This is 46 * achieved by "pushing" the data to the AudioTrack object using one of the 47 * {@link #write(byte[], int, int)}, {@link #write(short[], int, int)}, 48 * and {@link #write(float[], int, int, int)} methods. 49 * 50 * <p>An AudioTrack instance can operate under two modes: static or streaming.<br> 51 * In Streaming mode, the application writes a continuous stream of data to the AudioTrack, using 52 * one of the {@code write()} methods. These are blocking and return when the data has been 53 * transferred from the Java layer to the native layer and queued for playback. The streaming 54 * mode is most useful when playing blocks of audio data that for instance are: 55 * 56 * <ul> 57 * <li>too big to fit in memory because of the duration of the sound to play,</li> 58 * <li>too big to fit in memory because of the characteristics of the audio data 59 * (high sampling rate, bits per sample ...)</li> 60 * <li>received or generated while previously queued audio is playing.</li> 61 * </ul> 62 * 63 * The static mode should be chosen when dealing with short sounds that fit in memory and 64 * that need to be played with the smallest latency possible. The static mode will 65 * therefore be preferred for UI and game sounds that are played often, and with the 66 * smallest overhead possible. 67 * 68 * <p>Upon creation, an AudioTrack object initializes its associated audio buffer. 69 * The size of this buffer, specified during the construction, determines how long an AudioTrack 70 * can play before running out of data.<br> 71 * For an AudioTrack using the static mode, this size is the maximum size of the sound that can 72 * be played from it.<br> 73 * For the streaming mode, data will be written to the audio sink in chunks of 74 * sizes less than or equal to the total buffer size. 75 * 76 * AudioTrack is not final and thus permits subclasses, but such use is not recommended. 77 */ 78public class AudioTrack 79{ 80 //--------------------------------------------------------- 81 // Constants 82 //-------------------- 83 /** Minimum value for a linear gain or auxiliary effect level. 84 * This value must be exactly equal to 0.0f; do not change it. 85 */ 86 private static final float GAIN_MIN = 0.0f; 87 /** Maximum value for a linear gain or auxiliary effect level. 88 * This value must be greater than or equal to 1.0f. 89 */ 90 private static final float GAIN_MAX = 1.0f; 91 92 /** Minimum value for sample rate */ 93 private static final int SAMPLE_RATE_HZ_MIN = 4000; 94 /** Maximum value for sample rate */ 95 private static final int SAMPLE_RATE_HZ_MAX = 48000; 96 97 /** indicates AudioTrack state is stopped */ 98 public static final int PLAYSTATE_STOPPED = 1; // matches SL_PLAYSTATE_STOPPED 99 /** indicates AudioTrack state is paused */ 100 public static final int PLAYSTATE_PAUSED = 2; // matches SL_PLAYSTATE_PAUSED 101 /** indicates AudioTrack state is playing */ 102 public static final int PLAYSTATE_PLAYING = 3; // matches SL_PLAYSTATE_PLAYING 103 104 // keep these values in sync with android_media_AudioTrack.cpp 105 /** 106 * Creation mode where audio data is transferred from Java to the native layer 107 * only once before the audio starts playing. 108 */ 109 public static final int MODE_STATIC = 0; 110 /** 111 * Creation mode where audio data is streamed from Java to the native layer 112 * as the audio is playing. 113 */ 114 public static final int MODE_STREAM = 1; 115 116 /** 117 * State of an AudioTrack that was not successfully initialized upon creation. 118 */ 119 public static final int STATE_UNINITIALIZED = 0; 120 /** 121 * State of an AudioTrack that is ready to be used. 122 */ 123 public static final int STATE_INITIALIZED = 1; 124 /** 125 * State of a successfully initialized AudioTrack that uses static data, 126 * but that hasn't received that data yet. 127 */ 128 public static final int STATE_NO_STATIC_DATA = 2; 129 130 /** 131 * Denotes a successful operation. 132 */ 133 public static final int SUCCESS = AudioSystem.SUCCESS; 134 /** 135 * Denotes a generic operation failure. 136 */ 137 public static final int ERROR = AudioSystem.ERROR; 138 /** 139 * Denotes a failure due to the use of an invalid value. 140 */ 141 public static final int ERROR_BAD_VALUE = AudioSystem.BAD_VALUE; 142 /** 143 * Denotes a failure due to the improper use of a method. 144 */ 145 public static final int ERROR_INVALID_OPERATION = AudioSystem.INVALID_OPERATION; 146 147 // Error codes: 148 // to keep in sync with frameworks/base/core/jni/android_media_AudioTrack.cpp 149 private static final int ERROR_NATIVESETUP_AUDIOSYSTEM = -16; 150 private static final int ERROR_NATIVESETUP_INVALIDCHANNELMASK = -17; 151 private static final int ERROR_NATIVESETUP_INVALIDFORMAT = -18; 152 private static final int ERROR_NATIVESETUP_INVALIDSTREAMTYPE = -19; 153 private static final int ERROR_NATIVESETUP_NATIVEINITFAILED = -20; 154 155 // Events: 156 // to keep in sync with frameworks/av/include/media/AudioTrack.h 157 /** 158 * Event id denotes when playback head has reached a previously set marker. 159 */ 160 private static final int NATIVE_EVENT_MARKER = 3; 161 /** 162 * Event id denotes when previously set update period has elapsed during playback. 163 */ 164 private static final int NATIVE_EVENT_NEW_POS = 4; 165 166 private final static String TAG = "android.media.AudioTrack"; 167 168 169 /** @hide */ 170 @IntDef({ 171 WRITE_BLOCKING, 172 WRITE_NON_BLOCKING 173 }) 174 @Retention(RetentionPolicy.SOURCE) 175 public @interface WriteMode {} 176 177 /** 178 * The write mode indicating the write operation will block until all data has been written, 179 * to be used in {@link #write(ByteBuffer, int, int)} 180 */ 181 public final static int WRITE_BLOCKING = 0; 182 /** 183 * The write mode indicating the write operation will return immediately after 184 * queuing as much audio data for playback as possible without blocking, to be used in 185 * {@link #write(ByteBuffer, int, int)}. 186 */ 187 public final static int WRITE_NON_BLOCKING = 1; 188 189 //-------------------------------------------------------------------------- 190 // Member variables 191 //-------------------- 192 /** 193 * Indicates the state of the AudioTrack instance. 194 */ 195 private int mState = STATE_UNINITIALIZED; 196 /** 197 * Indicates the play state of the AudioTrack instance. 198 */ 199 private int mPlayState = PLAYSTATE_STOPPED; 200 /** 201 * Lock to make sure mPlayState updates are reflecting the actual state of the object. 202 */ 203 private final Object mPlayStateLock = new Object(); 204 /** 205 * Sizes of the native audio buffer. 206 */ 207 private int mNativeBufferSizeInBytes = 0; 208 private int mNativeBufferSizeInFrames = 0; 209 /** 210 * Handler for events coming from the native code. 211 */ 212 private NativeEventHandlerDelegate mEventHandlerDelegate; 213 /** 214 * Looper associated with the thread that creates the AudioTrack instance. 215 */ 216 private final Looper mInitializationLooper; 217 /** 218 * The audio data source sampling rate in Hz. 219 */ 220 private int mSampleRate; // initialized by all constructors 221 /** 222 * The number of audio output channels (1 is mono, 2 is stereo). 223 */ 224 private int mChannelCount = 1; 225 /** 226 * The audio channel mask. 227 */ 228 private int mChannels = AudioFormat.CHANNEL_OUT_MONO; 229 230 /** 231 * The type of the audio stream to play. See 232 * {@link AudioManager#STREAM_VOICE_CALL}, {@link AudioManager#STREAM_SYSTEM}, 233 * {@link AudioManager#STREAM_RING}, {@link AudioManager#STREAM_MUSIC}, 234 * {@link AudioManager#STREAM_ALARM}, {@link AudioManager#STREAM_NOTIFICATION}, and 235 * {@link AudioManager#STREAM_DTMF}. 236 */ 237 private int mStreamType = AudioManager.STREAM_MUSIC; 238 239 private final AudioAttributes mAttributes; 240 /** 241 * The way audio is consumed by the audio sink, streaming or static. 242 */ 243 private int mDataLoadMode = MODE_STREAM; 244 /** 245 * The current audio channel configuration. 246 */ 247 private int mChannelConfiguration = AudioFormat.CHANNEL_OUT_MONO; 248 /** 249 * The encoding of the audio samples. 250 * @see AudioFormat#ENCODING_PCM_8BIT 251 * @see AudioFormat#ENCODING_PCM_16BIT 252 * @see AudioFormat#ENCODING_PCM_FLOAT 253 */ 254 private int mAudioFormat = AudioFormat.ENCODING_PCM_16BIT; 255 /** 256 * Audio session ID 257 */ 258 private int mSessionId = AudioSystem.AUDIO_SESSION_ALLOCATE; 259 /** 260 * Reference to the app-ops service. 261 */ 262 private final IAppOpsService mAppOps; 263 264 //-------------------------------- 265 // Used exclusively by native code 266 //-------------------- 267 /** 268 * Accessed by native methods: provides access to C++ AudioTrack object. 269 */ 270 @SuppressWarnings("unused") 271 private long mNativeTrackInJavaObj; 272 /** 273 * Accessed by native methods: provides access to the JNI data (i.e. resources used by 274 * the native AudioTrack object, but not stored in it). 275 */ 276 @SuppressWarnings("unused") 277 private long mJniData; 278 279 280 //-------------------------------------------------------------------------- 281 // Constructor, Finalize 282 //-------------------- 283 /** 284 * Class constructor. 285 * @param streamType the type of the audio stream. See 286 * {@link AudioManager#STREAM_VOICE_CALL}, {@link AudioManager#STREAM_SYSTEM}, 287 * {@link AudioManager#STREAM_RING}, {@link AudioManager#STREAM_MUSIC}, 288 * {@link AudioManager#STREAM_ALARM}, and {@link AudioManager#STREAM_NOTIFICATION}. 289 * @param sampleRateInHz the initial source sample rate expressed in Hz. 290 * @param channelConfig describes the configuration of the audio channels. 291 * See {@link AudioFormat#CHANNEL_OUT_MONO} and 292 * {@link AudioFormat#CHANNEL_OUT_STEREO} 293 * @param audioFormat the format in which the audio data is represented. 294 * See {@link AudioFormat#ENCODING_PCM_16BIT}, 295 * {@link AudioFormat#ENCODING_PCM_8BIT}, 296 * and {@link AudioFormat#ENCODING_PCM_FLOAT}. 297 * @param bufferSizeInBytes the total size (in bytes) of the internal buffer where audio data is 298 * read from for playback. 299 * If track's creation mode is {@link #MODE_STREAM}, you can write data into 300 * this buffer in chunks less than or equal to this size, and it is typical to use 301 * chunks of 1/2 of the total size to permit double-buffering. 302 * If the track's creation mode is {@link #MODE_STATIC}, 303 * this is the maximum length sample, or audio clip, that can be played by this instance. 304 * See {@link #getMinBufferSize(int, int, int)} to determine the minimum required buffer size 305 * for the successful creation of an AudioTrack instance in streaming mode. Using values 306 * smaller than getMinBufferSize() will result in an initialization failure. 307 * @param mode streaming or static buffer. See {@link #MODE_STATIC} and {@link #MODE_STREAM} 308 * @throws java.lang.IllegalArgumentException 309 */ 310 public AudioTrack(int streamType, int sampleRateInHz, int channelConfig, int audioFormat, 311 int bufferSizeInBytes, int mode) 312 throws IllegalArgumentException { 313 this(streamType, sampleRateInHz, channelConfig, audioFormat, 314 bufferSizeInBytes, mode, AudioSystem.AUDIO_SESSION_ALLOCATE); 315 } 316 317 /** 318 * Class constructor with audio session. Use this constructor when the AudioTrack must be 319 * attached to a particular audio session. The primary use of the audio session ID is to 320 * associate audio effects to a particular instance of AudioTrack: if an audio session ID 321 * is provided when creating an AudioEffect, this effect will be applied only to audio tracks 322 * and media players in the same session and not to the output mix. 323 * When an AudioTrack is created without specifying a session, it will create its own session 324 * which can be retrieved by calling the {@link #getAudioSessionId()} method. 325 * If a non-zero session ID is provided, this AudioTrack will share effects attached to this 326 * session 327 * with all other media players or audio tracks in the same session, otherwise a new session 328 * will be created for this track if none is supplied. 329 * @param streamType the type of the audio stream. See 330 * {@link AudioManager#STREAM_VOICE_CALL}, {@link AudioManager#STREAM_SYSTEM}, 331 * {@link AudioManager#STREAM_RING}, {@link AudioManager#STREAM_MUSIC}, 332 * {@link AudioManager#STREAM_ALARM}, and {@link AudioManager#STREAM_NOTIFICATION}. 333 * @param sampleRateInHz the initial source sample rate expressed in Hz. 334 * @param channelConfig describes the configuration of the audio channels. 335 * See {@link AudioFormat#CHANNEL_OUT_MONO} and 336 * {@link AudioFormat#CHANNEL_OUT_STEREO} 337 * @param audioFormat the format in which the audio data is represented. 338 * See {@link AudioFormat#ENCODING_PCM_16BIT} and 339 * {@link AudioFormat#ENCODING_PCM_8BIT}, 340 * and {@link AudioFormat#ENCODING_PCM_FLOAT}. 341 * @param bufferSizeInBytes the total size (in bytes) of the buffer where audio data is read 342 * from for playback. If using the AudioTrack in streaming mode, you can write data into 343 * this buffer in smaller chunks than this size. If using the AudioTrack in static mode, 344 * this is the maximum size of the sound that will be played for this instance. 345 * See {@link #getMinBufferSize(int, int, int)} to determine the minimum required buffer size 346 * for the successful creation of an AudioTrack instance in streaming mode. Using values 347 * smaller than getMinBufferSize() will result in an initialization failure. 348 * @param mode streaming or static buffer. See {@link #MODE_STATIC} and {@link #MODE_STREAM} 349 * @param sessionId Id of audio session the AudioTrack must be attached to 350 * @throws java.lang.IllegalArgumentException 351 */ 352 public AudioTrack(int streamType, int sampleRateInHz, int channelConfig, int audioFormat, 353 int bufferSizeInBytes, int mode, int sessionId) 354 throws IllegalArgumentException { 355 // mState already == STATE_UNINITIALIZED 356 this((new AudioAttributes.Builder()) 357 .setLegacyStreamType(streamType) 358 .build(), 359 (new AudioFormat.Builder()) 360 .setChannelMask(channelConfig) 361 .setEncoding(audioFormat) 362 .setSampleRate(sampleRateInHz) 363 .build(), 364 bufferSizeInBytes, 365 mode, sessionId); 366 } 367 368 /** 369 * @hide 370 * CANDIDATE FOR PUBLIC API 371 * Constructor with AudioAttributes and AudioFormat 372 * @param aa 373 * @param format 374 * @param bufferSizeInBytes 375 * @param mode 376 * @param sessionId 377 */ 378 public AudioTrack(AudioAttributes attributes, AudioFormat format, int bufferSizeInBytes, 379 int mode, int sessionId) 380 throws IllegalArgumentException { 381 // mState already == STATE_UNINITIALIZED 382 383 // remember which looper is associated with the AudioTrack instantiation 384 Looper looper; 385 if ((looper = Looper.myLooper()) == null) { 386 looper = Looper.getMainLooper(); 387 } 388 389 int rate = 0; 390 if ((format.getPropertySetMask() & AudioFormat.AUDIO_FORMAT_HAS_PROPERTY_SAMPLE_RATE) != 0) 391 { 392 rate = format.getSampleRate(); 393 } else { 394 rate = AudioSystem.getPrimaryOutputSamplingRate(); 395 if (rate <= 0) { 396 rate = 44100; 397 } 398 } 399 int channelMask = AudioFormat.CHANNEL_OUT_FRONT_LEFT | AudioFormat.CHANNEL_OUT_FRONT_RIGHT; 400 if ((format.getPropertySetMask() & AudioFormat.AUDIO_FORMAT_HAS_PROPERTY_CHANNEL_MASK) != 0) 401 { 402 channelMask = format.getChannelMask(); 403 } 404 int encoding = AudioFormat.ENCODING_DEFAULT; 405 if ((format.getPropertySetMask() & AudioFormat.AUDIO_FORMAT_HAS_PROPERTY_ENCODING) != 0) { 406 encoding = format.getEncoding(); 407 } 408 audioParamCheck(rate, channelMask, encoding, mode); 409 mStreamType = AudioSystem.STREAM_DEFAULT; 410 411 audioBuffSizeCheck(bufferSizeInBytes); 412 413 mInitializationLooper = looper; 414 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE); 415 mAppOps = IAppOpsService.Stub.asInterface(b); 416 417 mAttributes = (new AudioAttributes.Builder(attributes).build()); 418 419 if (sessionId < 0) { 420 throw new IllegalArgumentException("Invalid audio session ID: "+sessionId); 421 } 422 423 int[] session = new int[1]; 424 session[0] = sessionId; 425 // native initialization 426 int initResult = native_setup(new WeakReference<AudioTrack>(this), mAttributes, 427 mSampleRate, mChannels, mAudioFormat, 428 mNativeBufferSizeInBytes, mDataLoadMode, session); 429 if (initResult != SUCCESS) { 430 loge("Error code "+initResult+" when initializing AudioTrack."); 431 return; // with mState == STATE_UNINITIALIZED 432 } 433 434 mSessionId = session[0]; 435 436 if (mDataLoadMode == MODE_STATIC) { 437 mState = STATE_NO_STATIC_DATA; 438 } else { 439 mState = STATE_INITIALIZED; 440 } 441 } 442 443 // mask of all the channels supported by this implementation 444 private static final int SUPPORTED_OUT_CHANNELS = 445 AudioFormat.CHANNEL_OUT_FRONT_LEFT | 446 AudioFormat.CHANNEL_OUT_FRONT_RIGHT | 447 AudioFormat.CHANNEL_OUT_FRONT_CENTER | 448 AudioFormat.CHANNEL_OUT_LOW_FREQUENCY | 449 AudioFormat.CHANNEL_OUT_BACK_LEFT | 450 AudioFormat.CHANNEL_OUT_BACK_RIGHT | 451 AudioFormat.CHANNEL_OUT_BACK_CENTER; 452 453 // Convenience method for the constructor's parameter checks. 454 // This is where constructor IllegalArgumentException-s are thrown 455 // postconditions: 456 // mChannelCount is valid 457 // mChannels is valid 458 // mAudioFormat is valid 459 // mSampleRate is valid 460 // mDataLoadMode is valid 461 private void audioParamCheck(int sampleRateInHz, 462 int channelConfig, int audioFormat, int mode) { 463 //-------------- 464 // sample rate, note these values are subject to change 465 if ( (sampleRateInHz < 4000) || (sampleRateInHz > 48000) ) { 466 throw new IllegalArgumentException(sampleRateInHz 467 + "Hz is not a supported sample rate."); 468 } 469 mSampleRate = sampleRateInHz; 470 471 //-------------- 472 // channel config 473 mChannelConfiguration = channelConfig; 474 475 switch (channelConfig) { 476 case AudioFormat.CHANNEL_OUT_DEFAULT: //AudioFormat.CHANNEL_CONFIGURATION_DEFAULT 477 case AudioFormat.CHANNEL_OUT_MONO: 478 case AudioFormat.CHANNEL_CONFIGURATION_MONO: 479 mChannelCount = 1; 480 mChannels = AudioFormat.CHANNEL_OUT_MONO; 481 break; 482 case AudioFormat.CHANNEL_OUT_STEREO: 483 case AudioFormat.CHANNEL_CONFIGURATION_STEREO: 484 mChannelCount = 2; 485 mChannels = AudioFormat.CHANNEL_OUT_STEREO; 486 break; 487 default: 488 if (!isMultichannelConfigSupported(channelConfig)) { 489 // input channel configuration features unsupported channels 490 throw new IllegalArgumentException("Unsupported channel configuration."); 491 } 492 mChannels = channelConfig; 493 mChannelCount = Integer.bitCount(channelConfig); 494 } 495 496 //-------------- 497 // audio format 498 if (audioFormat == AudioFormat.ENCODING_DEFAULT) { 499 audioFormat = AudioFormat.ENCODING_PCM_16BIT; 500 } 501 502 if (!AudioFormat.isValidEncoding(audioFormat)) { 503 throw new IllegalArgumentException("Unsupported audio encoding."); 504 } 505 mAudioFormat = audioFormat; 506 507 //-------------- 508 // audio load mode 509 if (((mode != MODE_STREAM) && (mode != MODE_STATIC)) || 510 ((mode != MODE_STREAM) && !AudioFormat.isEncodingLinearPcm(mAudioFormat))) { 511 throw new IllegalArgumentException("Invalid mode."); 512 } 513 mDataLoadMode = mode; 514 } 515 516 /** 517 * Convenience method to check that the channel configuration (a.k.a channel mask) is supported 518 * @param channelConfig the mask to validate 519 * @return false if the AudioTrack can't be used with such a mask 520 */ 521 private static boolean isMultichannelConfigSupported(int channelConfig) { 522 // check for unsupported channels 523 if ((channelConfig & SUPPORTED_OUT_CHANNELS) != channelConfig) { 524 loge("Channel configuration features unsupported channels"); 525 return false; 526 } 527 // check for unsupported multichannel combinations: 528 // - FL/FR must be present 529 // - L/R channels must be paired (e.g. no single L channel) 530 final int frontPair = 531 AudioFormat.CHANNEL_OUT_FRONT_LEFT | AudioFormat.CHANNEL_OUT_FRONT_RIGHT; 532 if ((channelConfig & frontPair) != frontPair) { 533 loge("Front channels must be present in multichannel configurations"); 534 return false; 535 } 536 final int backPair = 537 AudioFormat.CHANNEL_OUT_BACK_LEFT | AudioFormat.CHANNEL_OUT_BACK_RIGHT; 538 if ((channelConfig & backPair) != 0) { 539 if ((channelConfig & backPair) != backPair) { 540 loge("Rear channels can't be used independently"); 541 return false; 542 } 543 } 544 return true; 545 } 546 547 548 // Convenience method for the constructor's audio buffer size check. 549 // preconditions: 550 // mChannelCount is valid 551 // mAudioFormat is valid 552 // postcondition: 553 // mNativeBufferSizeInBytes is valid (multiple of frame size, positive) 554 private void audioBuffSizeCheck(int audioBufferSize) { 555 // NB: this section is only valid with PCM data. 556 // To update when supporting compressed formats 557 int frameSizeInBytes; 558 if (AudioFormat.isEncodingLinearPcm(mAudioFormat)) { 559 frameSizeInBytes = mChannelCount 560 * (AudioFormat.getBytesPerSample(mAudioFormat)); 561 } else { 562 frameSizeInBytes = 1; 563 } 564 if ((audioBufferSize % frameSizeInBytes != 0) || (audioBufferSize < 1)) { 565 throw new IllegalArgumentException("Invalid audio buffer size."); 566 } 567 568 mNativeBufferSizeInBytes = audioBufferSize; 569 mNativeBufferSizeInFrames = audioBufferSize / frameSizeInBytes; 570 } 571 572 573 /** 574 * Releases the native AudioTrack resources. 575 */ 576 public void release() { 577 // even though native_release() stops the native AudioTrack, we need to stop 578 // AudioTrack subclasses too. 579 try { 580 stop(); 581 } catch(IllegalStateException ise) { 582 // don't raise an exception, we're releasing the resources. 583 } 584 native_release(); 585 mState = STATE_UNINITIALIZED; 586 } 587 588 @Override 589 protected void finalize() { 590 native_finalize(); 591 } 592 593 //-------------------------------------------------------------------------- 594 // Getters 595 //-------------------- 596 /** 597 * Returns the minimum gain value, which is the constant 0.0. 598 * Gain values less than 0.0 will be clamped to 0.0. 599 * <p>The word "volume" in the API name is historical; this is actually a linear gain. 600 * @return the minimum value, which is the constant 0.0. 601 */ 602 static public float getMinVolume() { 603 return GAIN_MIN; 604 } 605 606 /** 607 * Returns the maximum gain value, which is greater than or equal to 1.0. 608 * Gain values greater than the maximum will be clamped to the maximum. 609 * <p>The word "volume" in the API name is historical; this is actually a gain. 610 * expressed as a linear multiplier on sample values, where a maximum value of 1.0 611 * corresponds to a gain of 0 dB (sample values left unmodified). 612 * @return the maximum value, which is greater than or equal to 1.0. 613 */ 614 static public float getMaxVolume() { 615 return GAIN_MAX; 616 } 617 618 /** 619 * Returns the configured audio data sample rate in Hz 620 */ 621 public int getSampleRate() { 622 return mSampleRate; 623 } 624 625 /** 626 * Returns the current playback rate in Hz. 627 */ 628 public int getPlaybackRate() { 629 return native_get_playback_rate(); 630 } 631 632 /** 633 * Returns the configured audio data format. See {@link AudioFormat#ENCODING_PCM_16BIT} 634 * and {@link AudioFormat#ENCODING_PCM_8BIT}. 635 */ 636 public int getAudioFormat() { 637 return mAudioFormat; 638 } 639 640 /** 641 * Returns the type of audio stream this AudioTrack is configured for. 642 * Compare the result against {@link AudioManager#STREAM_VOICE_CALL}, 643 * {@link AudioManager#STREAM_SYSTEM}, {@link AudioManager#STREAM_RING}, 644 * {@link AudioManager#STREAM_MUSIC}, {@link AudioManager#STREAM_ALARM}, 645 * {@link AudioManager#STREAM_NOTIFICATION}, or {@link AudioManager#STREAM_DTMF}. 646 */ 647 public int getStreamType() { 648 return mStreamType; 649 } 650 651 /** 652 * Returns the configured channel configuration. 653 * See {@link AudioFormat#CHANNEL_OUT_MONO} 654 * and {@link AudioFormat#CHANNEL_OUT_STEREO}. 655 */ 656 public int getChannelConfiguration() { 657 return mChannelConfiguration; 658 } 659 660 /** 661 * Returns the configured number of channels. 662 */ 663 public int getChannelCount() { 664 return mChannelCount; 665 } 666 667 /** 668 * Returns the state of the AudioTrack instance. This is useful after the 669 * AudioTrack instance has been created to check if it was initialized 670 * properly. This ensures that the appropriate resources have been acquired. 671 * @see #STATE_INITIALIZED 672 * @see #STATE_NO_STATIC_DATA 673 * @see #STATE_UNINITIALIZED 674 */ 675 public int getState() { 676 return mState; 677 } 678 679 /** 680 * Returns the playback state of the AudioTrack instance. 681 * @see #PLAYSTATE_STOPPED 682 * @see #PLAYSTATE_PAUSED 683 * @see #PLAYSTATE_PLAYING 684 */ 685 public int getPlayState() { 686 synchronized (mPlayStateLock) { 687 return mPlayState; 688 } 689 } 690 691 /** 692 * Returns the "native frame count", derived from the bufferSizeInBytes specified at 693 * creation time and converted to frame units. 694 * If track's creation mode is {@link #MODE_STATIC}, 695 * it is equal to the specified bufferSizeInBytes converted to frame units. 696 * If track's creation mode is {@link #MODE_STREAM}, 697 * it is typically greater than or equal to the specified bufferSizeInBytes converted to frame 698 * units; it may be rounded up to a larger value if needed by the target device implementation. 699 * @deprecated Only accessible by subclasses, which are not recommended for AudioTrack. 700 * See {@link AudioManager#getProperty(String)} for key 701 * {@link AudioManager#PROPERTY_OUTPUT_FRAMES_PER_BUFFER}. 702 */ 703 @Deprecated 704 protected int getNativeFrameCount() { 705 return native_get_native_frame_count(); 706 } 707 708 /** 709 * Returns marker position expressed in frames. 710 * @return marker position in wrapping frame units similar to {@link #getPlaybackHeadPosition}, 711 * or zero if marker is disabled. 712 */ 713 public int getNotificationMarkerPosition() { 714 return native_get_marker_pos(); 715 } 716 717 /** 718 * Returns the notification update period expressed in frames. 719 * Zero means that no position update notifications are being delivered. 720 */ 721 public int getPositionNotificationPeriod() { 722 return native_get_pos_update_period(); 723 } 724 725 /** 726 * Returns the playback head position expressed in frames. 727 * Though the "int" type is signed 32-bits, the value should be reinterpreted as if it is 728 * unsigned 32-bits. That is, the next position after 0x7FFFFFFF is (int) 0x80000000. 729 * This is a continuously advancing counter. It will wrap (overflow) periodically, 730 * for example approximately once every 27:03:11 hours:minutes:seconds at 44.1 kHz. 731 * It is reset to zero by flush(), reload(), and stop(). 732 */ 733 public int getPlaybackHeadPosition() { 734 return native_get_position(); 735 } 736 737 /** 738 * Returns this track's estimated latency in milliseconds. This includes the latency due 739 * to AudioTrack buffer size, AudioMixer (if any) and audio hardware driver. 740 * 741 * DO NOT UNHIDE. The existing approach for doing A/V sync has too many problems. We need 742 * a better solution. 743 * @hide 744 */ 745 public int getLatency() { 746 return native_get_latency(); 747 } 748 749 /** 750 * Returns the output sample rate in Hz for the specified stream type. 751 */ 752 static public int getNativeOutputSampleRate(int streamType) { 753 return native_get_output_sample_rate(streamType); 754 } 755 756 /** 757 * Returns the minimum buffer size required for the successful creation of an AudioTrack 758 * object to be created in the {@link #MODE_STREAM} mode. Note that this size doesn't 759 * guarantee a smooth playback under load, and higher values should be chosen according to 760 * the expected frequency at which the buffer will be refilled with additional data to play. 761 * For example, if you intend to dynamically set the source sample rate of an AudioTrack 762 * to a higher value than the initial source sample rate, be sure to configure the buffer size 763 * based on the highest planned sample rate. 764 * @param sampleRateInHz the source sample rate expressed in Hz. 765 * @param channelConfig describes the configuration of the audio channels. 766 * See {@link AudioFormat#CHANNEL_OUT_MONO} and 767 * {@link AudioFormat#CHANNEL_OUT_STEREO} 768 * @param audioFormat the format in which the audio data is represented. 769 * See {@link AudioFormat#ENCODING_PCM_16BIT} and 770 * {@link AudioFormat#ENCODING_PCM_8BIT}, 771 * and {@link AudioFormat#ENCODING_PCM_FLOAT}. 772 * @return {@link #ERROR_BAD_VALUE} if an invalid parameter was passed, 773 * or {@link #ERROR} if unable to query for output properties, 774 * or the minimum buffer size expressed in bytes. 775 */ 776 static public int getMinBufferSize(int sampleRateInHz, int channelConfig, int audioFormat) { 777 int channelCount = 0; 778 switch(channelConfig) { 779 case AudioFormat.CHANNEL_OUT_MONO: 780 case AudioFormat.CHANNEL_CONFIGURATION_MONO: 781 channelCount = 1; 782 break; 783 case AudioFormat.CHANNEL_OUT_STEREO: 784 case AudioFormat.CHANNEL_CONFIGURATION_STEREO: 785 channelCount = 2; 786 break; 787 default: 788 if ((channelConfig & SUPPORTED_OUT_CHANNELS) != channelConfig) { 789 // input channel configuration features unsupported channels 790 loge("getMinBufferSize(): Invalid channel configuration."); 791 return ERROR_BAD_VALUE; 792 } else { 793 channelCount = Integer.bitCount(channelConfig); 794 } 795 } 796 797 if (!AudioFormat.isValidEncoding(audioFormat)) { 798 loge("getMinBufferSize(): Invalid audio format."); 799 return ERROR_BAD_VALUE; 800 } 801 802 // sample rate, note these values are subject to change 803 if ( (sampleRateInHz < SAMPLE_RATE_HZ_MIN) || (sampleRateInHz > SAMPLE_RATE_HZ_MAX) ) { 804 loge("getMinBufferSize(): " + sampleRateInHz + " Hz is not a supported sample rate."); 805 return ERROR_BAD_VALUE; 806 } 807 808 int size = native_get_min_buff_size(sampleRateInHz, channelCount, audioFormat); 809 if (size <= 0) { 810 loge("getMinBufferSize(): error querying hardware"); 811 return ERROR; 812 } 813 else { 814 return size; 815 } 816 } 817 818 /** 819 * Returns the audio session ID. 820 * 821 * @return the ID of the audio session this AudioTrack belongs to. 822 */ 823 public int getAudioSessionId() { 824 return mSessionId; 825 } 826 827 /** 828 * Poll for a timestamp on demand. 829 * <p> 830 * If you need to track timestamps during initial warmup or after a routing or mode change, 831 * you should request a new timestamp once per second until the reported timestamps 832 * show that the audio clock is stable. 833 * Thereafter, query for a new timestamp approximately once every 10 seconds to once per minute. 834 * Calling this method more often is inefficient. 835 * It is also counter-productive to call this method more often than recommended, 836 * because the short-term differences between successive timestamp reports are not meaningful. 837 * If you need a high-resolution mapping between frame position and presentation time, 838 * consider implementing that at application level, based on low-resolution timestamps. 839 * <p> 840 * The audio data at the returned position may either already have been 841 * presented, or may have not yet been presented but is committed to be presented. 842 * It is not possible to request the time corresponding to a particular position, 843 * or to request the (fractional) position corresponding to a particular time. 844 * If you need such features, consider implementing them at application level. 845 * 846 * @param timestamp a reference to a non-null AudioTimestamp instance allocated 847 * and owned by caller. 848 * @return true if a timestamp is available, or false if no timestamp is available. 849 * If a timestamp if available, 850 * the AudioTimestamp instance is filled in with a position in frame units, together 851 * with the estimated time when that frame was presented or is committed to 852 * be presented. 853 * In the case that no timestamp is available, any supplied instance is left unaltered. 854 * A timestamp may be temporarily unavailable while the audio clock is stabilizing, 855 * or during and immediately after a route change. 856 */ 857 // Add this text when the "on new timestamp" API is added: 858 // Use if you need to get the most recent timestamp outside of the event callback handler. 859 public boolean getTimestamp(AudioTimestamp timestamp) 860 { 861 if (timestamp == null) { 862 throw new IllegalArgumentException(); 863 } 864 // It's unfortunate, but we have to either create garbage every time or use synchronized 865 long[] longArray = new long[2]; 866 int ret = native_get_timestamp(longArray); 867 if (ret != SUCCESS) { 868 return false; 869 } 870 timestamp.framePosition = longArray[0]; 871 timestamp.nanoTime = longArray[1]; 872 return true; 873 } 874 875 876 //-------------------------------------------------------------------------- 877 // Initialization / configuration 878 //-------------------- 879 /** 880 * Sets the listener the AudioTrack notifies when a previously set marker is reached or 881 * for each periodic playback head position update. 882 * Notifications will be received in the same thread as the one in which the AudioTrack 883 * instance was created. 884 * @param listener 885 */ 886 public void setPlaybackPositionUpdateListener(OnPlaybackPositionUpdateListener listener) { 887 setPlaybackPositionUpdateListener(listener, null); 888 } 889 890 /** 891 * Sets the listener the AudioTrack notifies when a previously set marker is reached or 892 * for each periodic playback head position update. 893 * Use this method to receive AudioTrack events in the Handler associated with another 894 * thread than the one in which you created the AudioTrack instance. 895 * @param listener 896 * @param handler the Handler that will receive the event notification messages. 897 */ 898 public void setPlaybackPositionUpdateListener(OnPlaybackPositionUpdateListener listener, 899 Handler handler) { 900 if (listener != null) { 901 mEventHandlerDelegate = new NativeEventHandlerDelegate(this, listener, handler); 902 } else { 903 mEventHandlerDelegate = null; 904 } 905 } 906 907 908 private static float clampGainOrLevel(float gainOrLevel) { 909 if (Float.isNaN(gainOrLevel)) { 910 throw new IllegalArgumentException(); 911 } 912 if (gainOrLevel < GAIN_MIN) { 913 gainOrLevel = GAIN_MIN; 914 } else if (gainOrLevel > GAIN_MAX) { 915 gainOrLevel = GAIN_MAX; 916 } 917 return gainOrLevel; 918 } 919 920 921 /** 922 * Sets the specified left and right output gain values on the AudioTrack. 923 * <p>Gain values are clamped to the closed interval [0.0, max] where 924 * max is the value of {@link #getMaxVolume}. 925 * A value of 0.0 results in zero gain (silence), and 926 * a value of 1.0 means unity gain (signal unchanged). 927 * The default value is 1.0 meaning unity gain. 928 * <p>The word "volume" in the API name is historical; this is actually a linear gain. 929 * @param leftGain output gain for the left channel. 930 * @param rightGain output gain for the right channel 931 * @return error code or success, see {@link #SUCCESS}, 932 * {@link #ERROR_INVALID_OPERATION} 933 * @deprecated Applications should use {@link #setVolume} instead, as it 934 * more gracefully scales down to mono, and up to multi-channel content beyond stereo. 935 */ 936 public int setStereoVolume(float leftGain, float rightGain) { 937 if (isRestricted()) { 938 return SUCCESS; 939 } 940 if (mState == STATE_UNINITIALIZED) { 941 return ERROR_INVALID_OPERATION; 942 } 943 944 leftGain = clampGainOrLevel(leftGain); 945 rightGain = clampGainOrLevel(rightGain); 946 947 native_setVolume(leftGain, rightGain); 948 949 return SUCCESS; 950 } 951 952 953 /** 954 * Sets the specified output gain value on all channels of this track. 955 * <p>Gain values are clamped to the closed interval [0.0, max] where 956 * max is the value of {@link #getMaxVolume}. 957 * A value of 0.0 results in zero gain (silence), and 958 * a value of 1.0 means unity gain (signal unchanged). 959 * The default value is 1.0 meaning unity gain. 960 * <p>This API is preferred over {@link #setStereoVolume}, as it 961 * more gracefully scales down to mono, and up to multi-channel content beyond stereo. 962 * <p>The word "volume" in the API name is historical; this is actually a linear gain. 963 * @param gain output gain for all channels. 964 * @return error code or success, see {@link #SUCCESS}, 965 * {@link #ERROR_INVALID_OPERATION} 966 */ 967 public int setVolume(float gain) { 968 return setStereoVolume(gain, gain); 969 } 970 971 972 /** 973 * Sets the playback sample rate for this track. This sets the sampling rate at which 974 * the audio data will be consumed and played back 975 * (as set by the sampleRateInHz parameter in the 976 * {@link #AudioTrack(int, int, int, int, int, int)} constructor), 977 * not the original sampling rate of the 978 * content. For example, setting it to half the sample rate of the content will cause the 979 * playback to last twice as long, but will also result in a pitch shift down by one octave. 980 * The valid sample rate range is from 1 Hz to twice the value returned by 981 * {@link #getNativeOutputSampleRate(int)}. 982 * @param sampleRateInHz the sample rate expressed in Hz 983 * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE}, 984 * {@link #ERROR_INVALID_OPERATION} 985 */ 986 public int setPlaybackRate(int sampleRateInHz) { 987 if (mState != STATE_INITIALIZED) { 988 return ERROR_INVALID_OPERATION; 989 } 990 if (sampleRateInHz <= 0) { 991 return ERROR_BAD_VALUE; 992 } 993 return native_set_playback_rate(sampleRateInHz); 994 } 995 996 997 /** 998 * Sets the position of the notification marker. At most one marker can be active. 999 * @param markerInFrames marker position in wrapping frame units similar to 1000 * {@link #getPlaybackHeadPosition}, or zero to disable the marker. 1001 * To set a marker at a position which would appear as zero due to wraparound, 1002 * a workaround is to use a non-zero position near zero, such as -1 or 1. 1003 * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE}, 1004 * {@link #ERROR_INVALID_OPERATION} 1005 */ 1006 public int setNotificationMarkerPosition(int markerInFrames) { 1007 if (mState == STATE_UNINITIALIZED) { 1008 return ERROR_INVALID_OPERATION; 1009 } 1010 return native_set_marker_pos(markerInFrames); 1011 } 1012 1013 1014 /** 1015 * Sets the period for the periodic notification event. 1016 * @param periodInFrames update period expressed in frames 1017 * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_INVALID_OPERATION} 1018 */ 1019 public int setPositionNotificationPeriod(int periodInFrames) { 1020 if (mState == STATE_UNINITIALIZED) { 1021 return ERROR_INVALID_OPERATION; 1022 } 1023 return native_set_pos_update_period(periodInFrames); 1024 } 1025 1026 1027 /** 1028 * Sets the playback head position. 1029 * The track must be stopped or paused for the position to be changed, 1030 * and must use the {@link #MODE_STATIC} mode. 1031 * @param positionInFrames playback head position expressed in frames 1032 * Zero corresponds to start of buffer. 1033 * The position must not be greater than the buffer size in frames, or negative. 1034 * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE}, 1035 * {@link #ERROR_INVALID_OPERATION} 1036 */ 1037 public int setPlaybackHeadPosition(int positionInFrames) { 1038 if (mDataLoadMode == MODE_STREAM || mState != STATE_INITIALIZED || 1039 getPlayState() == PLAYSTATE_PLAYING) { 1040 return ERROR_INVALID_OPERATION; 1041 } 1042 if (!(0 <= positionInFrames && positionInFrames <= mNativeBufferSizeInFrames)) { 1043 return ERROR_BAD_VALUE; 1044 } 1045 return native_set_position(positionInFrames); 1046 } 1047 1048 /** 1049 * Sets the loop points and the loop count. The loop can be infinite. 1050 * Similarly to setPlaybackHeadPosition, 1051 * the track must be stopped or paused for the loop points to be changed, 1052 * and must use the {@link #MODE_STATIC} mode. 1053 * @param startInFrames loop start marker expressed in frames 1054 * Zero corresponds to start of buffer. 1055 * The start marker must not be greater than or equal to the buffer size in frames, or negative. 1056 * @param endInFrames loop end marker expressed in frames 1057 * The total buffer size in frames corresponds to end of buffer. 1058 * The end marker must not be greater than the buffer size in frames. 1059 * For looping, the end marker must not be less than or equal to the start marker, 1060 * but to disable looping 1061 * it is permitted for start marker, end marker, and loop count to all be 0. 1062 * @param loopCount the number of times the loop is looped. 1063 * A value of -1 means infinite looping, and 0 disables looping. 1064 * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE}, 1065 * {@link #ERROR_INVALID_OPERATION} 1066 */ 1067 public int setLoopPoints(int startInFrames, int endInFrames, int loopCount) { 1068 if (mDataLoadMode == MODE_STREAM || mState != STATE_INITIALIZED || 1069 getPlayState() == PLAYSTATE_PLAYING) { 1070 return ERROR_INVALID_OPERATION; 1071 } 1072 if (loopCount == 0) { 1073 ; // explicitly allowed as an exception to the loop region range check 1074 } else if (!(0 <= startInFrames && startInFrames < mNativeBufferSizeInFrames && 1075 startInFrames < endInFrames && endInFrames <= mNativeBufferSizeInFrames)) { 1076 return ERROR_BAD_VALUE; 1077 } 1078 return native_set_loop(startInFrames, endInFrames, loopCount); 1079 } 1080 1081 /** 1082 * Sets the initialization state of the instance. This method was originally intended to be used 1083 * in an AudioTrack subclass constructor to set a subclass-specific post-initialization state. 1084 * However, subclasses of AudioTrack are no longer recommended, so this method is obsolete. 1085 * @param state the state of the AudioTrack instance 1086 * @deprecated Only accessible by subclasses, which are not recommended for AudioTrack. 1087 */ 1088 @Deprecated 1089 protected void setState(int state) { 1090 mState = state; 1091 } 1092 1093 1094 //--------------------------------------------------------- 1095 // Transport control methods 1096 //-------------------- 1097 /** 1098 * Starts playing an AudioTrack. 1099 * If track's creation mode is {@link #MODE_STATIC}, you must have called write() prior. 1100 * 1101 * @throws IllegalStateException 1102 */ 1103 public void play() 1104 throws IllegalStateException { 1105 if (mState != STATE_INITIALIZED) { 1106 throw new IllegalStateException("play() called on uninitialized AudioTrack."); 1107 } 1108 if (isRestricted()) { 1109 setVolume(0); 1110 } 1111 synchronized(mPlayStateLock) { 1112 native_start(); 1113 mPlayState = PLAYSTATE_PLAYING; 1114 } 1115 } 1116 1117 private boolean isRestricted() { 1118 try { 1119 final int mode = mAppOps.checkAudioOperation(AppOpsManager.OP_PLAY_AUDIO, mStreamType, 1120 Process.myUid(), ActivityThread.currentPackageName()); 1121 return mode != AppOpsManager.MODE_ALLOWED; 1122 } catch (RemoteException e) { 1123 return false; 1124 } 1125 } 1126 1127 /** 1128 * Stops playing the audio data. 1129 * When used on an instance created in {@link #MODE_STREAM} mode, audio will stop playing 1130 * after the last buffer that was written has been played. For an immediate stop, use 1131 * {@link #pause()}, followed by {@link #flush()} to discard audio data that hasn't been played 1132 * back yet. 1133 * @throws IllegalStateException 1134 */ 1135 public void stop() 1136 throws IllegalStateException { 1137 if (mState != STATE_INITIALIZED) { 1138 throw new IllegalStateException("stop() called on uninitialized AudioTrack."); 1139 } 1140 1141 // stop playing 1142 synchronized(mPlayStateLock) { 1143 native_stop(); 1144 mPlayState = PLAYSTATE_STOPPED; 1145 } 1146 } 1147 1148 /** 1149 * Pauses the playback of the audio data. Data that has not been played 1150 * back will not be discarded. Subsequent calls to {@link #play} will play 1151 * this data back. See {@link #flush()} to discard this data. 1152 * 1153 * @throws IllegalStateException 1154 */ 1155 public void pause() 1156 throws IllegalStateException { 1157 if (mState != STATE_INITIALIZED) { 1158 throw new IllegalStateException("pause() called on uninitialized AudioTrack."); 1159 } 1160 //logd("pause()"); 1161 1162 // pause playback 1163 synchronized(mPlayStateLock) { 1164 native_pause(); 1165 mPlayState = PLAYSTATE_PAUSED; 1166 } 1167 } 1168 1169 1170 //--------------------------------------------------------- 1171 // Audio data supply 1172 //-------------------- 1173 1174 /** 1175 * Flushes the audio data currently queued for playback. Any data that has 1176 * not been played back will be discarded. No-op if not stopped or paused, 1177 * or if the track's creation mode is not {@link #MODE_STREAM}. 1178 */ 1179 public void flush() { 1180 if (mState == STATE_INITIALIZED) { 1181 // flush the data in native layer 1182 native_flush(); 1183 } 1184 1185 } 1186 1187 /** 1188 * Writes the audio data to the audio sink for playback (streaming mode), 1189 * or copies audio data for later playback (static buffer mode). 1190 * In streaming mode, will block until all data has been written to the audio sink. 1191 * In static buffer mode, copies the data to the buffer starting at offset 0. 1192 * Note that the actual playback of this data might occur after this function 1193 * returns. This function is thread safe with respect to {@link #stop} calls, 1194 * in which case all of the specified data might not be written to the audio sink. 1195 * 1196 * @param audioData the array that holds the data to play. 1197 * @param offsetInBytes the offset expressed in bytes in audioData where the data to play 1198 * starts. 1199 * @param sizeInBytes the number of bytes to read in audioData after the offset. 1200 * @return the number of bytes that were written or {@link #ERROR_INVALID_OPERATION} 1201 * if the object wasn't properly initialized, or {@link #ERROR_BAD_VALUE} if 1202 * the parameters don't resolve to valid data and indexes, or 1203 * {@link AudioManager#ERROR_DEAD_OBJECT} if the AudioTrack is not valid anymore and 1204 * needs to be recreated. 1205 */ 1206 1207 public int write(byte[] audioData, int offsetInBytes, int sizeInBytes) { 1208 1209 if (mState == STATE_UNINITIALIZED || mAudioFormat == AudioFormat.ENCODING_PCM_FLOAT) { 1210 return ERROR_INVALID_OPERATION; 1211 } 1212 1213 if ( (audioData == null) || (offsetInBytes < 0 ) || (sizeInBytes < 0) 1214 || (offsetInBytes + sizeInBytes < 0) // detect integer overflow 1215 || (offsetInBytes + sizeInBytes > audioData.length)) { 1216 return ERROR_BAD_VALUE; 1217 } 1218 1219 int ret = native_write_byte(audioData, offsetInBytes, sizeInBytes, mAudioFormat, 1220 true /*isBlocking*/); 1221 1222 if ((mDataLoadMode == MODE_STATIC) 1223 && (mState == STATE_NO_STATIC_DATA) 1224 && (ret > 0)) { 1225 // benign race with respect to other APIs that read mState 1226 mState = STATE_INITIALIZED; 1227 } 1228 1229 return ret; 1230 } 1231 1232 1233 /** 1234 * Writes the audio data to the audio sink for playback (streaming mode), 1235 * or copies audio data for later playback (static buffer mode). 1236 * In streaming mode, will block until all data has been written to the audio sink. 1237 * In static buffer mode, copies the data to the buffer starting at offset 0. 1238 * Note that the actual playback of this data might occur after this function 1239 * returns. This function is thread safe with respect to {@link #stop} calls, 1240 * in which case all of the specified data might not be written to the audio sink. 1241 * 1242 * @param audioData the array that holds the data to play. 1243 * @param offsetInShorts the offset expressed in shorts in audioData where the data to play 1244 * starts. 1245 * @param sizeInShorts the number of shorts to read in audioData after the offset. 1246 * @return the number of shorts that were written or {@link #ERROR_INVALID_OPERATION} 1247 * if the object wasn't properly initialized, or {@link #ERROR_BAD_VALUE} if 1248 * the parameters don't resolve to valid data and indexes. 1249 */ 1250 1251 public int write(short[] audioData, int offsetInShorts, int sizeInShorts) { 1252 1253 if (mState == STATE_UNINITIALIZED || mAudioFormat != AudioFormat.ENCODING_PCM_16BIT) { 1254 return ERROR_INVALID_OPERATION; 1255 } 1256 1257 if ( (audioData == null) || (offsetInShorts < 0 ) || (sizeInShorts < 0) 1258 || (offsetInShorts + sizeInShorts < 0) // detect integer overflow 1259 || (offsetInShorts + sizeInShorts > audioData.length)) { 1260 return ERROR_BAD_VALUE; 1261 } 1262 1263 int ret = native_write_short(audioData, offsetInShorts, sizeInShorts, mAudioFormat); 1264 1265 if ((mDataLoadMode == MODE_STATIC) 1266 && (mState == STATE_NO_STATIC_DATA) 1267 && (ret > 0)) { 1268 // benign race with respect to other APIs that read mState 1269 mState = STATE_INITIALIZED; 1270 } 1271 1272 return ret; 1273 } 1274 1275 1276 /** 1277 * Writes the audio data to the audio sink for playback (streaming mode), 1278 * or copies audio data for later playback (static buffer mode). 1279 * In static buffer mode, copies the data to the buffer starting at offset 0, 1280 * and the write mode is ignored. 1281 * In streaming mode, the blocking behavior will depend on the write mode. 1282 * <p> 1283 * Note that the actual playback of this data might occur after this function 1284 * returns. This function is thread safe with respect to {@link #stop} calls, 1285 * in which case all of the specified data might not be written to the audio sink. 1286 * <p> 1287 * @param audioData the array that holds the data to play. 1288 * The implementation does not clip for sample values within the nominal range 1289 * [-1.0f, 1.0f], provided that all gains in the audio pipeline are 1290 * less than or equal to unity (1.0f), and in the absence of post-processing effects 1291 * that could add energy, such as reverb. For the convenience of applications 1292 * that compute samples using filters with non-unity gain, 1293 * sample values +3 dB beyond the nominal range are permitted. 1294 * However such values may eventually be limited or clipped, depending on various gains 1295 * and later processing in the audio path. Therefore applications are encouraged 1296 * to provide samples values within the nominal range. 1297 * @param offsetInFloats the offset, expressed as a number of floats, 1298 * in audioData where the data to play starts. 1299 * @param sizeInFloats the number of floats to read in audioData after the offset. 1300 * @param writeMode one of {@link #WRITE_BLOCKING}, {@link #WRITE_NON_BLOCKING}. It has no 1301 * effect in static mode. 1302 * <BR>With {@link #WRITE_BLOCKING}, the write will block until all data has been written 1303 * to the audio sink. 1304 * <BR>With {@link #WRITE_NON_BLOCKING}, the write will return immediately after 1305 * queuing as much audio data for playback as possible without blocking. 1306 * @return the number of floats that were written, or {@link #ERROR_INVALID_OPERATION} 1307 * if the object wasn't properly initialized, or {@link #ERROR_BAD_VALUE} if 1308 * the parameters don't resolve to valid data and indexes. 1309 */ 1310 public int write(float[] audioData, int offsetInFloats, int sizeInFloats, 1311 @WriteMode int writeMode) { 1312 1313 if (mState == STATE_UNINITIALIZED) { 1314 Log.e(TAG, "AudioTrack.write() called in invalid state STATE_UNINITIALIZED"); 1315 return ERROR_INVALID_OPERATION; 1316 } 1317 1318 if (mAudioFormat != AudioFormat.ENCODING_PCM_FLOAT) { 1319 Log.e(TAG, "AudioTrack.write(float[] ...) requires format ENCODING_PCM_FLOAT"); 1320 return ERROR_INVALID_OPERATION; 1321 } 1322 1323 if ((writeMode != WRITE_BLOCKING) && (writeMode != WRITE_NON_BLOCKING)) { 1324 Log.e(TAG, "AudioTrack.write() called with invalid blocking mode"); 1325 return ERROR_BAD_VALUE; 1326 } 1327 1328 if ( (audioData == null) || (offsetInFloats < 0 ) || (sizeInFloats < 0) 1329 || (offsetInFloats + sizeInFloats < 0) // detect integer overflow 1330 || (offsetInFloats + sizeInFloats > audioData.length)) { 1331 Log.e(TAG, "AudioTrack.write() called with invalid array, offset, or size"); 1332 return ERROR_BAD_VALUE; 1333 } 1334 1335 int ret = native_write_float(audioData, offsetInFloats, sizeInFloats, mAudioFormat, 1336 writeMode == WRITE_BLOCKING); 1337 1338 if ((mDataLoadMode == MODE_STATIC) 1339 && (mState == STATE_NO_STATIC_DATA) 1340 && (ret > 0)) { 1341 // benign race with respect to other APIs that read mState 1342 mState = STATE_INITIALIZED; 1343 } 1344 1345 return ret; 1346 } 1347 1348 1349 /** 1350 * Writes the audio data to the audio sink for playback (streaming mode), 1351 * or copies audio data for later playback (static buffer mode). 1352 * In static buffer mode, copies the data to the buffer starting at its 0 offset, and the write 1353 * mode is ignored. 1354 * In streaming mode, the blocking behavior will depend on the write mode. 1355 * @param audioData the buffer that holds the data to play, starting at the position reported 1356 * by <code>audioData.position()</code>. 1357 * <BR>Note that upon return, the buffer position (<code>audioData.position()</code>) will 1358 * have been advanced to reflect the amount of data that was successfully written to 1359 * the AudioTrack. 1360 * @param sizeInBytes number of bytes to write. 1361 * <BR>Note this may differ from <code>audioData.remaining()</code>, but cannot exceed it. 1362 * @param writeMode one of {@link #WRITE_BLOCKING}, {@link #WRITE_NON_BLOCKING}. It has no 1363 * effect in static mode. 1364 * <BR>With {@link #WRITE_BLOCKING}, the write will block until all data has been written 1365 * to the audio sink. 1366 * <BR>With {@link #WRITE_NON_BLOCKING}, the write will return immediately after 1367 * queuing as much audio data for playback as possible without blocking. 1368 * @return 0 or a positive number of bytes that were written, or 1369 * {@link #ERROR_BAD_VALUE}, {@link #ERROR_INVALID_OPERATION} 1370 */ 1371 public int write(ByteBuffer audioData, int sizeInBytes, 1372 @WriteMode int writeMode) { 1373 1374 if (mState == STATE_UNINITIALIZED) { 1375 Log.e(TAG, "AudioTrack.write() called in invalid state STATE_UNINITIALIZED"); 1376 return ERROR_INVALID_OPERATION; 1377 } 1378 1379 if ((writeMode != WRITE_BLOCKING) && (writeMode != WRITE_NON_BLOCKING)) { 1380 Log.e(TAG, "AudioTrack.write() called with invalid blocking mode"); 1381 return ERROR_BAD_VALUE; 1382 } 1383 1384 if ( (audioData == null) || (sizeInBytes < 0) || (sizeInBytes > audioData.remaining())) { 1385 Log.e(TAG, "AudioTrack.write() called with invalid size (" + sizeInBytes + ") value"); 1386 return ERROR_BAD_VALUE; 1387 } 1388 1389 int ret = 0; 1390 if (audioData.isDirect()) { 1391 ret = native_write_native_bytes(audioData, 1392 audioData.position(), sizeInBytes, mAudioFormat, 1393 writeMode == WRITE_BLOCKING); 1394 } else { 1395 ret = native_write_byte(NioUtils.unsafeArray(audioData), 1396 NioUtils.unsafeArrayOffset(audioData) + audioData.position(), 1397 sizeInBytes, mAudioFormat, 1398 writeMode == WRITE_BLOCKING); 1399 } 1400 1401 if ((mDataLoadMode == MODE_STATIC) 1402 && (mState == STATE_NO_STATIC_DATA) 1403 && (ret > 0)) { 1404 // benign race with respect to other APIs that read mState 1405 mState = STATE_INITIALIZED; 1406 } 1407 1408 if (ret > 0) { 1409 audioData.position(audioData.position() + ret); 1410 } 1411 1412 return ret; 1413 } 1414 1415 /** 1416 * Notifies the native resource to reuse the audio data already loaded in the native 1417 * layer, that is to rewind to start of buffer. 1418 * The track's creation mode must be {@link #MODE_STATIC}. 1419 * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE}, 1420 * {@link #ERROR_INVALID_OPERATION} 1421 */ 1422 public int reloadStaticData() { 1423 if (mDataLoadMode == MODE_STREAM || mState != STATE_INITIALIZED) { 1424 return ERROR_INVALID_OPERATION; 1425 } 1426 return native_reload_static(); 1427 } 1428 1429 //-------------------------------------------------------------------------- 1430 // Audio effects management 1431 //-------------------- 1432 1433 /** 1434 * Attaches an auxiliary effect to the audio track. A typical auxiliary 1435 * effect is a reverberation effect which can be applied on any sound source 1436 * that directs a certain amount of its energy to this effect. This amount 1437 * is defined by setAuxEffectSendLevel(). 1438 * {@see #setAuxEffectSendLevel(float)}. 1439 * <p>After creating an auxiliary effect (e.g. 1440 * {@link android.media.audiofx.EnvironmentalReverb}), retrieve its ID with 1441 * {@link android.media.audiofx.AudioEffect#getId()} and use it when calling 1442 * this method to attach the audio track to the effect. 1443 * <p>To detach the effect from the audio track, call this method with a 1444 * null effect id. 1445 * 1446 * @param effectId system wide unique id of the effect to attach 1447 * @return error code or success, see {@link #SUCCESS}, 1448 * {@link #ERROR_INVALID_OPERATION}, {@link #ERROR_BAD_VALUE} 1449 */ 1450 public int attachAuxEffect(int effectId) { 1451 if (mState == STATE_UNINITIALIZED) { 1452 return ERROR_INVALID_OPERATION; 1453 } 1454 return native_attachAuxEffect(effectId); 1455 } 1456 1457 /** 1458 * Sets the send level of the audio track to the attached auxiliary effect 1459 * {@link #attachAuxEffect(int)}. Effect levels 1460 * are clamped to the closed interval [0.0, max] where 1461 * max is the value of {@link #getMaxVolume}. 1462 * A value of 0.0 results in no effect, and a value of 1.0 is full send. 1463 * <p>By default the send level is 0.0f, so even if an effect is attached to the player 1464 * this method must be called for the effect to be applied. 1465 * <p>Note that the passed level value is a linear scalar. UI controls should be scaled 1466 * logarithmically: the gain applied by audio framework ranges from -72dB to at least 0dB, 1467 * so an appropriate conversion from linear UI input x to level is: 1468 * x == 0 -> level = 0 1469 * 0 < x <= R -> level = 10^(72*(x-R)/20/R) 1470 * 1471 * @param level linear send level 1472 * @return error code or success, see {@link #SUCCESS}, 1473 * {@link #ERROR_INVALID_OPERATION}, {@link #ERROR} 1474 */ 1475 public int setAuxEffectSendLevel(float level) { 1476 if (isRestricted()) { 1477 return SUCCESS; 1478 } 1479 if (mState == STATE_UNINITIALIZED) { 1480 return ERROR_INVALID_OPERATION; 1481 } 1482 level = clampGainOrLevel(level); 1483 int err = native_setAuxEffectSendLevel(level); 1484 return err == 0 ? SUCCESS : ERROR; 1485 } 1486 1487 //--------------------------------------------------------- 1488 // Interface definitions 1489 //-------------------- 1490 /** 1491 * Interface definition for a callback to be invoked when the playback head position of 1492 * an AudioTrack has reached a notification marker or has increased by a certain period. 1493 */ 1494 public interface OnPlaybackPositionUpdateListener { 1495 /** 1496 * Called on the listener to notify it that the previously set marker has been reached 1497 * by the playback head. 1498 */ 1499 void onMarkerReached(AudioTrack track); 1500 1501 /** 1502 * Called on the listener to periodically notify it that the playback head has reached 1503 * a multiple of the notification period. 1504 */ 1505 void onPeriodicNotification(AudioTrack track); 1506 } 1507 1508 //--------------------------------------------------------- 1509 // Inner classes 1510 //-------------------- 1511 /** 1512 * Helper class to handle the forwarding of native events to the appropriate listener 1513 * (potentially) handled in a different thread 1514 */ 1515 private class NativeEventHandlerDelegate { 1516 private final Handler mHandler; 1517 1518 NativeEventHandlerDelegate(final AudioTrack track, 1519 final OnPlaybackPositionUpdateListener listener, 1520 Handler handler) { 1521 // find the looper for our new event handler 1522 Looper looper; 1523 if (handler != null) { 1524 looper = handler.getLooper(); 1525 } else { 1526 // no given handler, use the looper the AudioTrack was created in 1527 looper = mInitializationLooper; 1528 } 1529 1530 // construct the event handler with this looper 1531 if (looper != null) { 1532 // implement the event handler delegate 1533 mHandler = new Handler(looper) { 1534 @Override 1535 public void handleMessage(Message msg) { 1536 if (track == null) { 1537 return; 1538 } 1539 switch(msg.what) { 1540 case NATIVE_EVENT_MARKER: 1541 if (listener != null) { 1542 listener.onMarkerReached(track); 1543 } 1544 break; 1545 case NATIVE_EVENT_NEW_POS: 1546 if (listener != null) { 1547 listener.onPeriodicNotification(track); 1548 } 1549 break; 1550 default: 1551 loge("Unknown native event type: " + msg.what); 1552 break; 1553 } 1554 } 1555 }; 1556 } else { 1557 mHandler = null; 1558 } 1559 } 1560 1561 Handler getHandler() { 1562 return mHandler; 1563 } 1564 } 1565 1566 1567 //--------------------------------------------------------- 1568 // Java methods called from the native side 1569 //-------------------- 1570 @SuppressWarnings("unused") 1571 private static void postEventFromNative(Object audiotrack_ref, 1572 int what, int arg1, int arg2, Object obj) { 1573 //logd("Event posted from the native side: event="+ what + " args="+ arg1+" "+arg2); 1574 AudioTrack track = (AudioTrack)((WeakReference)audiotrack_ref).get(); 1575 if (track == null) { 1576 return; 1577 } 1578 1579 NativeEventHandlerDelegate delegate = track.mEventHandlerDelegate; 1580 if (delegate != null) { 1581 Handler handler = delegate.getHandler(); 1582 if (handler != null) { 1583 Message m = handler.obtainMessage(what, arg1, arg2, obj); 1584 handler.sendMessage(m); 1585 } 1586 } 1587 1588 } 1589 1590 1591 //--------------------------------------------------------- 1592 // Native methods called from the Java side 1593 //-------------------- 1594 1595 // post-condition: mStreamType is overwritten with a value 1596 // that reflects the audio attributes (e.g. an AudioAttributes object with a usage of 1597 // AudioAttributes.USAGE_MEDIA will map to AudioManager.STREAM_MUSIC 1598 private native final int native_setup(Object /*WeakReference<AudioTrack>*/ audiotrack_this, 1599 Object /*AudioAttributes*/ attributes, 1600 int sampleRate, int channelMask, int audioFormat, 1601 int buffSizeInBytes, int mode, int[] sessionId); 1602 1603 private native final void native_finalize(); 1604 1605 private native final void native_release(); 1606 1607 private native final void native_start(); 1608 1609 private native final void native_stop(); 1610 1611 private native final void native_pause(); 1612 1613 private native final void native_flush(); 1614 1615 private native final int native_write_byte(byte[] audioData, 1616 int offsetInBytes, int sizeInBytes, int format, 1617 boolean isBlocking); 1618 1619 private native final int native_write_short(short[] audioData, 1620 int offsetInShorts, int sizeInShorts, int format); 1621 1622 private native final int native_write_float(float[] audioData, 1623 int offsetInFloats, int sizeInFloats, int format, 1624 boolean isBlocking); 1625 1626 private native final int native_write_native_bytes(Object audioData, 1627 int positionInBytes, int sizeInBytes, int format, boolean blocking); 1628 1629 private native final int native_reload_static(); 1630 1631 private native final int native_get_native_frame_count(); 1632 1633 private native final void native_setVolume(float leftVolume, float rightVolume); 1634 1635 private native final int native_set_playback_rate(int sampleRateInHz); 1636 private native final int native_get_playback_rate(); 1637 1638 private native final int native_set_marker_pos(int marker); 1639 private native final int native_get_marker_pos(); 1640 1641 private native final int native_set_pos_update_period(int updatePeriod); 1642 private native final int native_get_pos_update_period(); 1643 1644 private native final int native_set_position(int position); 1645 private native final int native_get_position(); 1646 1647 private native final int native_get_latency(); 1648 1649 // longArray must be a non-null array of length >= 2 1650 // [0] is assigned the frame position 1651 // [1] is assigned the time in CLOCK_MONOTONIC nanoseconds 1652 private native final int native_get_timestamp(long[] longArray); 1653 1654 private native final int native_set_loop(int start, int end, int loopCount); 1655 1656 static private native final int native_get_output_sample_rate(int streamType); 1657 static private native final int native_get_min_buff_size( 1658 int sampleRateInHz, int channelConfig, int audioFormat); 1659 1660 private native final int native_attachAuxEffect(int effectId); 1661 private native final int native_setAuxEffectSendLevel(float level); 1662 1663 //--------------------------------------------------------- 1664 // Utility methods 1665 //------------------ 1666 1667 private static void logd(String msg) { 1668 Log.d(TAG, msg); 1669 } 1670 1671 private static void loge(String msg) { 1672 Log.e(TAG, msg); 1673 } 1674 1675} 1676