public class

AudioTrack

extends Object
java.lang.Object
   ↳ android.media.AudioTrack

Class Overview

The AudioTrack class manages and plays a single audio resource for Java applications. It allows to stream PCM audio buffers to the audio hardware for playback. This is achieved by "pushing" the data to the AudioTrack object using one of the write(byte[], int, int) and write(short[], int, int) methods.

An AudioTrack instance can operate under two modes: static or streaming.
In Streaming mode, the application writes a continuous stream of data to the AudioTrack, using one of the write() methods. These are blocking and return when the data has been transferred from the Java layer to the native layer and queued for playback. The streaming mode is most useful when playing blocks of audio data that for instance are:

  • too big to fit in memory because of the duration of the sound to play,
  • too big to fit in memory because of the characteristics of the audio data (high sampling rate, bits per sample ...)
  • received or generated while previously queued audio is playing.
The static mode is to be chosen when dealing with short sounds that fit in memory and that need to be played with the smallest latency possible. AudioTrack instances in static mode can play the sound without the need to transfer the audio data from Java to native layer each time the sound is to be played. The static mode will therefore be preferred for UI and game sounds that are played often, and with the smallest overhead possible.

Upon creation, an AudioTrack object initializes its associated audio buffer. The size of this buffer, specified during the construction, determines how long an AudioTrack can play before running out of data.
For an AudioTrack using the static mode, this size is the maximum size of the sound that can be played from it.
For the streaming mode, data will be written to the hardware in chunks of sizes inferior to the total buffer size.

Summary

Nested Classes
interface AudioTrack.OnPlaybackPositionUpdateListener Interface definition for a callback to be invoked when the playback head position of an AudioTrack has reached a notification marker or has increased by a certain period. 
Constants
int ERROR Denotes a generic operation failure.
int ERROR_BAD_VALUE Denotes a failure due to the use of an invalid value.
int ERROR_INVALID_OPERATION Denotes a failure due to the improper use of a method.
int MODE_STATIC Creation mode where audio data is transferred from Java to the native layer only once before the audio starts playing.
int MODE_STREAM Creation mode where audio data is streamed from Java to the native layer as the audio is playing.
int PLAYSTATE_PAUSED indicates AudioTrack state is paused
int PLAYSTATE_PLAYING indicates AudioTrack state is playing
int PLAYSTATE_STOPPED indicates AudioTrack state is stopped
int STATE_INITIALIZED State of an AudioTrack that is ready to be used.
int STATE_NO_STATIC_DATA State of a successfully initialized AudioTrack that uses static data, but that hasn't received that data yet.
int STATE_UNINITIALIZED State of an AudioTrack that was not successfully initialized upon creation.
int SUCCESS Denotes a successful operation.
Public Constructors
AudioTrack(int streamType, int sampleRateInHz, int channelConfig, int audioFormat, int bufferSizeInBytes, int mode)
Class constructor.
AudioTrack(int streamType, int sampleRateInHz, int channelConfig, int audioFormat, int bufferSizeInBytes, int mode, int sessionId)
Class constructor with audio session.
Public Methods
int attachAuxEffect(int effectId)
Attaches an auxiliary effect to the audio track.
void flush()
Flushes the audio data currently queued for playback.
int getAudioFormat()
Returns the configured audio data format.
int getAudioSessionId()
Returns the audio session ID.
int getChannelConfiguration()
Returns the configured channel configuration.
int getChannelCount()
Returns the configured number of channels.
static float getMaxVolume()
Returns the maximum valid volume value.
static int getMinBufferSize(int sampleRateInHz, int channelConfig, int audioFormat)
Returns the minimum buffer size required for the successful creation of an AudioTrack object to be created in the MODE_STREAM mode.
static float getMinVolume()
Returns the minimum valid volume value.
static int getNativeOutputSampleRate(int streamType)
Returns the hardware output sample rate
int getNotificationMarkerPosition()
Returns marker position expressed in frames.
int getPlayState()
Returns the playback state of the AudioTrack instance.
int getPlaybackHeadPosition()
Returns the playback head position expressed in frames
int getPlaybackRate()
Returns the current playback rate in Hz.
int getPositionNotificationPeriod()
Returns the notification update period expressed in frames.
int getSampleRate()
Returns the configured audio data sample rate in Hz
int getState()
Returns the state of the AudioTrack instance.
int getStreamType()
Returns the type of audio stream this AudioTrack is configured for.
void pause()
Pauses the playback of the audio data.
void play()
Starts playing an AudioTrack.
void release()
Releases the native AudioTrack resources.
int reloadStaticData()
Notifies the native resource to reuse the audio data already loaded in the native layer.
int setAuxEffectSendLevel(float level)
Sets the send level of the audio track to the attached auxiliary effect .
int setLoopPoints(int startInFrames, int endInFrames, int loopCount)
Sets the loop points and the loop count.
int setNotificationMarkerPosition(int markerInFrames)
Sets the position of the notification marker.
int setPlaybackHeadPosition(int positionInFrames)
Sets the playback head position.
void setPlaybackPositionUpdateListener(AudioTrack.OnPlaybackPositionUpdateListener listener)
Sets the listener the AudioTrack notifies when a previously set marker is reached or for each periodic playback head position update.
void setPlaybackPositionUpdateListener(AudioTrack.OnPlaybackPositionUpdateListener listener, Handler handler)
Sets the listener the AudioTrack notifies when a previously set marker is reached or for each periodic playback head position update.
int setPlaybackRate(int sampleRateInHz)
Sets the playback sample rate for this track.
int setPositionNotificationPeriod(int periodInFrames)
Sets the period for the periodic notification event.
int setStereoVolume(float leftVolume, float rightVolume)
Sets the specified left/right output volume values on the AudioTrack.
void stop()
Stops playing the audio data.
int write(short[] audioData, int offsetInShorts, int sizeInShorts)
Writes the audio data to the audio hardware for playback.
int write(byte[] audioData, int offsetInBytes, int sizeInBytes)
Writes the audio data to the audio hardware for playback.
Protected Methods
void finalize()
Called before the object's memory is reclaimed by the VM.
int getNativeFrameCount()
Returns the native frame count used by the hardware.
void setState(int state)
Sets the initialization state of the instance.
[Expand]
Inherited Methods
From class java.lang.Object

Constants

public static final int ERROR

Since: API Level 3

Denotes a generic operation failure.

Constant Value: -1 (0xffffffff)

public static final int ERROR_BAD_VALUE

Since: API Level 3

Denotes a failure due to the use of an invalid value.

Constant Value: -2 (0xfffffffe)

public static final int ERROR_INVALID_OPERATION

Since: API Level 3

Denotes a failure due to the improper use of a method.

Constant Value: -3 (0xfffffffd)

public static final int MODE_STATIC

Since: API Level 3

Creation mode where audio data is transferred from Java to the native layer only once before the audio starts playing.

Constant Value: 0 (0x00000000)

public static final int MODE_STREAM

Since: API Level 3

Creation mode where audio data is streamed from Java to the native layer as the audio is playing.

Constant Value: 1 (0x00000001)

public static final int PLAYSTATE_PAUSED

Since: API Level 3

indicates AudioTrack state is paused

Constant Value: 2 (0x00000002)

public static final int PLAYSTATE_PLAYING

Since: API Level 3

indicates AudioTrack state is playing

Constant Value: 3 (0x00000003)

public static final int PLAYSTATE_STOPPED

Since: API Level 3

indicates AudioTrack state is stopped

Constant Value: 1 (0x00000001)

public static final int STATE_INITIALIZED

Since: API Level 3

State of an AudioTrack that is ready to be used.

Constant Value: 1 (0x00000001)

public static final int STATE_NO_STATIC_DATA

Since: API Level 3

State of a successfully initialized AudioTrack that uses static data, but that hasn't received that data yet.

Constant Value: 2 (0x00000002)

public static final int STATE_UNINITIALIZED

Since: API Level 3

State of an AudioTrack that was not successfully initialized upon creation.

Constant Value: 0 (0x00000000)

public static final int SUCCESS

Since: API Level 3

Denotes a successful operation.

Constant Value: 0 (0x00000000)

Public Constructors

public AudioTrack (int streamType, int sampleRateInHz, int channelConfig, int audioFormat, int bufferSizeInBytes, int mode)

Since: API Level 3

Class constructor.

Parameters
streamType the type of the audio stream. See STREAM_VOICE_CALL, STREAM_SYSTEM, STREAM_RING, STREAM_MUSIC and STREAM_ALARM
sampleRateInHz the sample rate expressed in Hertz. Examples of rates are (but not limited to) 44100, 22050 and 11025.
channelConfig describes the configuration of the audio channels. See CHANNEL_OUT_MONO and CHANNEL_OUT_STEREO
audioFormat the format in which the audio data is represented. See ENCODING_PCM_16BIT and ENCODING_PCM_8BIT
bufferSizeInBytes the total size (in bytes) of the buffer where audio data is read from for playback. If using the AudioTrack in streaming mode, you can write data into this buffer in smaller chunks than this size. If using the AudioTrack in static mode, this is the maximum size of the sound that will be played for this instance. See getMinBufferSize(int, int, int) to determine the minimum required buffer size for the successful creation of an AudioTrack instance in streaming mode. Using values smaller than getMinBufferSize() will result in an initialization failure.
mode streaming or static buffer. See MODE_STATIC and MODE_STREAM

public AudioTrack (int streamType, int sampleRateInHz, int channelConfig, int audioFormat, int bufferSizeInBytes, int mode, int sessionId)

Since: API Level 9

Class constructor with audio session. Use this constructor when the AudioTrack must be attached to a particular audio session. The primary use of the audio session ID is to associate audio effects to a particular instance of AudioTrack: if an audio session ID is provided when creating an AudioEffect, this effect will be applied only to audio tracks and media players in the same session and not to the output mix. When an AudioTrack is created without specifying a session, it will create its own session which can be retreived by calling the getAudioSessionId() method. If a session ID is provided, this AudioTrack will share effects attached to this session with all other media players or audio tracks in the same session.

Parameters
streamType the type of the audio stream. See STREAM_VOICE_CALL, STREAM_SYSTEM, STREAM_RING, STREAM_MUSIC and STREAM_ALARM
sampleRateInHz the sample rate expressed in Hertz. Examples of rates are (but not limited to) 44100, 22050 and 11025.
channelConfig describes the configuration of the audio channels. See CHANNEL_OUT_MONO and CHANNEL_OUT_STEREO
audioFormat the format in which the audio data is represented. See ENCODING_PCM_16BIT and ENCODING_PCM_8BIT
bufferSizeInBytes the total size (in bytes) of the buffer where audio data is read from for playback. If using the AudioTrack in streaming mode, you can write data into this buffer in smaller chunks than this size. If using the AudioTrack in static mode, this is the maximum size of the sound that will be played for this instance. See getMinBufferSize(int, int, int) to determine the minimum required buffer size for the successful creation of an AudioTrack instance in streaming mode. Using values smaller than getMinBufferSize() will result in an initialization failure.
mode streaming or static buffer. See MODE_STATIC and MODE_STREAM
sessionId Id of audio session the AudioTrack must be attached to

Public Methods

public int attachAuxEffect (int effectId)

Since: API Level 9

Attaches an auxiliary effect to the audio track. A typical auxiliary effect is a reverberation effect which can be applied on any sound source that directs a certain amount of its energy to this effect. This amount is defined by setAuxEffectSendLevel(). .

After creating an auxiliary effect (e.g. EnvironmentalReverb), retrieve its ID with getId() and use it when calling this method to attach the audio track to the effect.

To detach the effect from the audio track, call this method with a null effect id.

Parameters
effectId system wide unique id of the effect to attach
Returns

public void flush ()

Since: API Level 3

Flushes the audio data currently queued for playback.

public int getAudioFormat ()

Since: API Level 3

Returns the configured audio data format. See ENCODING_PCM_16BIT and ENCODING_PCM_8BIT.

public int getAudioSessionId ()

Since: API Level 9

Returns the audio session ID.

Returns
  • the ID of the audio session this AudioTrack belongs to.

public int getChannelConfiguration ()

Since: API Level 3

Returns the configured channel configuration. See CHANNEL_OUT_MONO and CHANNEL_OUT_STEREO.

public int getChannelCount ()

Since: API Level 3

Returns the configured number of channels.

public static float getMaxVolume ()

Since: API Level 3

Returns the maximum valid volume value. Volume values set above this one will be clamped at this value.

Returns
  • the maximum volume expressed as a linear attenuation.

public static int getMinBufferSize (int sampleRateInHz, int channelConfig, int audioFormat)

Since: API Level 3

Returns the minimum buffer size required for the successful creation of an AudioTrack object to be created in the MODE_STREAM mode. Note that this size doesn't guarantee a smooth playback under load, and higher values should be chosen according to the expected frequency at which the buffer will be refilled with additional data to play.

Parameters
sampleRateInHz the sample rate expressed in Hertz.
channelConfig describes the configuration of the audio channels. See CHANNEL_OUT_MONO and CHANNEL_OUT_STEREO
audioFormat the format in which the audio data is represented. See ENCODING_PCM_16BIT and ENCODING_PCM_8BIT
Returns
  • ERROR_BAD_VALUE if an invalid parameter was passed, or ERROR if the implementation was unable to query the hardware for its output properties, or the minimum buffer size expressed in bytes.

public static float getMinVolume ()

Since: API Level 3

Returns the minimum valid volume value. Volume values set under this one will be clamped at this value.

Returns
  • the minimum volume expressed as a linear attenuation.

public static int getNativeOutputSampleRate (int streamType)

Since: API Level 3

Returns the hardware output sample rate

public int getNotificationMarkerPosition ()

Since: API Level 3

Returns marker position expressed in frames.

public int getPlayState ()

Since: API Level 3

Returns the playback state of the AudioTrack instance.

public int getPlaybackHeadPosition ()

Since: API Level 3

Returns the playback head position expressed in frames

public int getPlaybackRate ()

Since: API Level 3

Returns the current playback rate in Hz.

public int getPositionNotificationPeriod ()

Since: API Level 3

Returns the notification update period expressed in frames.

public int getSampleRate ()

Since: API Level 3

Returns the configured audio data sample rate in Hz

public int getState ()

Since: API Level 3

Returns the state of the AudioTrack instance. This is useful after the AudioTrack instance has been created to check if it was initialized properly. This ensures that the appropriate hardware resources have been acquired.

public int getStreamType ()

Since: API Level 3

Returns the type of audio stream this AudioTrack is configured for. Compare the result against STREAM_VOICE_CALL, STREAM_SYSTEM, STREAM_RING, STREAM_MUSIC or STREAM_ALARM

public void pause ()

Since: API Level 3

Pauses the playback of the audio data.

public void play ()

Since: API Level 3

Starts playing an AudioTrack.

public void release ()

Since: API Level 3

Releases the native AudioTrack resources.

public int reloadStaticData ()

Since: API Level 3

Notifies the native resource to reuse the audio data already loaded in the native layer. This call is only valid with AudioTrack instances that don't use the streaming model.

Returns

public int setAuxEffectSendLevel (float level)

Since: API Level 9

Sets the send level of the audio track to the attached auxiliary effect . The level value range is 0 to 1.0.

By default the send level is 0, so even if an effect is attached to the player this method must be called for the effect to be applied.

Note that the passed level value is a raw scalar. UI controls should be scaled logarithmically: the gain applied by audio framework ranges from -72dB to 0dB, so an appropriate conversion from linear UI input x to level is: x == 0 -> level = 0 0 < x <= R -> level = 10^(72*(x-R)/20/R)

Parameters
level send level scalar
Returns

public int setLoopPoints (int startInFrames, int endInFrames, int loopCount)

Since: API Level 3

Sets the loop points and the loop count. The loop can be infinite.

Parameters
startInFrames loop start marker expressed in frames
endInFrames loop end marker expressed in frames
loopCount the number of times the loop is looped. A value of -1 means infinite looping.
Returns

public int setNotificationMarkerPosition (int markerInFrames)

Since: API Level 3

Sets the position of the notification marker.

Parameters
markerInFrames marker in frames
Returns

public int setPlaybackHeadPosition (int positionInFrames)

Since: API Level 3

Sets the playback head position. The track must be stopped for the position to be changed.

Parameters
positionInFrames playback head position expressed in frames
Returns

public void setPlaybackPositionUpdateListener (AudioTrack.OnPlaybackPositionUpdateListener listener)

Since: API Level 3

Sets the listener the AudioTrack notifies when a previously set marker is reached or for each periodic playback head position update. Notifications will be received in the same thread as the one in which the AudioTrack instance was created.

public void setPlaybackPositionUpdateListener (AudioTrack.OnPlaybackPositionUpdateListener listener, Handler handler)

Since: API Level 3

Sets the listener the AudioTrack notifies when a previously set marker is reached or for each periodic playback head position update. Use this method to receive AudioTrack events in the Handler associated with another thread than the one in which you created the AudioTrack instance.

Parameters
handler the Handler that will receive the event notification messages.

public int setPlaybackRate (int sampleRateInHz)

Since: API Level 3

Sets the playback sample rate for this track. This sets the sampling rate at which the audio data will be consumed and played back, not the original sampling rate of the content. Setting it to half the sample rate of the content will cause the playback to last twice as long, but will also result in a negative pitch shift. The valid sample rate range if from 1Hz to twice the value returned by getNativeOutputSampleRate(int).

Parameters
sampleRateInHz the sample rate expressed in Hz
Returns

public int setPositionNotificationPeriod (int periodInFrames)

Since: API Level 3

Sets the period for the periodic notification event.

Parameters
periodInFrames update period expressed in frames
Returns

public int setStereoVolume (float leftVolume, float rightVolume)

Since: API Level 3

Sets the specified left/right output volume values on the AudioTrack. Values are clamped to the (getMinVolume(), getMaxVolume()) interval if outside this range.

Parameters
leftVolume output attenuation for the left channel. A value of 0.0f is silence, a value of 1.0f is no attenuation.
rightVolume output attenuation for the right channel
Returns

public void stop ()

Since: API Level 3

Stops playing the audio data.

public int write (short[] audioData, int offsetInShorts, int sizeInShorts)

Since: API Level 3

Writes the audio data to the audio hardware for playback.

Parameters
audioData the array that holds the data to play.
offsetInShorts the offset expressed in shorts in audioData where the data to play starts.
sizeInShorts the number of bytes to read in audioData after the offset.
Returns

public int write (byte[] audioData, int offsetInBytes, int sizeInBytes)

Since: API Level 3

Writes the audio data to the audio hardware for playback.

Parameters
audioData the array that holds the data to play.
offsetInBytes the offset expressed in bytes in audioData where the data to play starts.
sizeInBytes the number of bytes to read in audioData after the offset.
Returns

Protected Methods

protected void finalize ()

Since: API Level 3

Called before the object's memory is reclaimed by the VM. This can only happen once the garbage collector has detected that the object is no longer reachable by any thread of the running application.

The method can be used to free system resources or perform other cleanup before the object is garbage collected. The default implementation of the method is empty, which is also expected by the VM, but subclasses can override finalize() as required. Uncaught exceptions which are thrown during the execution of this method cause it to terminate immediately but are otherwise ignored.

Note that the VM does guarantee that finalize() is called at most once for any object, but it doesn't guarantee when (if at all) finalize() will be called. For example, object B's finalize() can delay the execution of object A's finalize() method and therefore it can delay the reclamation of A's memory. To be safe, use a ReferenceQueue, because it provides more control over the way the VM deals with references during garbage collection.

protected int getNativeFrameCount ()

Since: API Level 3

Returns the native frame count used by the hardware.

protected void setState (int state)

Since: API Level 3

Sets the initialization state of the instance. To be used in an AudioTrack subclass constructor to set a subclass-specific post-initialization state.

Parameters
state the state of the AudioTrack instance