Android APIs
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 streaming of PCM audio buffers to the audio sink for playback. This is achieved by "pushing" the data to the AudioTrack object using one of the write(byte[], int, int), write(short[], int, int), and write(float[], int, 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 should be chosen when dealing with short sounds that fit in memory and that need to be played with the smallest latency possible. 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 audio sink in chunks of sizes less than or equal to the total buffer size. AudioTrack is not final and thus permits subclasses, but such use is not recommended.

Summary

Nested Classes
class AudioTrack.Builder Builder class for AudioTrack objects. 
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. 
interface AudioTrack.OnRoutingChangedListener Defines the interface by which applications can receive notifications of routing changes for the associated AudioTrack
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.
int WRITE_BLOCKING The write mode indicating the write operation will block until all data has been written, to be used as the actual value of the writeMode parameter in write(byte[], int, int, int), write(short[], int, int, int), write(float[], int, int, int), write(ByteBuffer, int, int), and write(ByteBuffer, int, int, long).
int WRITE_NON_BLOCKING The write mode indicating the write operation will return immediately after queuing as much audio data for playback as possible without blocking, to be used as the actual value of the writeMode parameter in write(ByteBuffer, int, int), write(short[], int, int, int), write(float[], int, int, int), write(ByteBuffer, int, int), and write(ByteBuffer, int, int, long).
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.
AudioTrack(AudioAttributes attributes, AudioFormat format, int bufferSizeInBytes, int mode, int sessionId)
Class constructor with AudioAttributes and AudioFormat.
Public Methods
void addOnRoutingChangedListener(AudioTrack.OnRoutingChangedListener listener, Handler handler)
Adds an AudioTrack.OnRoutingChangedListener to receive notifications of routing changes on this AudioTrack.
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 encoding.
int getAudioSessionId()
Returns the audio session ID.
int getBufferSizeInFrames()
Returns the frame count of the native AudioTrack buffer.
int getChannelConfiguration()
Returns the configured channel position mask.
int getChannelCount()
Returns the configured number of channels.
AudioFormat getFormat()
Returns the configured AudioTrack format.
static float getMaxVolume()
Returns the maximum gain value, which is greater than or equal to 1.0.
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 gain value, which is the constant 0.0.
static int getNativeOutputSampleRate(int streamType)
Returns the output sample rate in Hz for the specified stream type.
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.
PlaybackParams getPlaybackParams()
Returns the current playback parameters.
int getPlaybackRate()
Returns the current playback sample rate rate in Hz.
int getPositionNotificationPeriod()
Returns the notification update period expressed in frames.
AudioDeviceInfo getPreferredDevice()
Returns the selected output specified by setPreferredDevice(AudioDeviceInfo).
AudioDeviceInfo getRoutedDevice()
Returns an AudioDeviceInfo identifying the current routing of this AudioTrack.
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.
boolean getTimestamp(AudioTimestamp timestamp)
Poll for a timestamp on demand.
void pause()
Pauses the playback of the audio data.
void play()
Starts playing an AudioTrack.
void release()
Releases the native AudioTrack resources.
int reloadStaticData()
Sets the playback head position within the static buffer to zero, that is it rewinds to start of static buffer.
void removeOnRoutingChangedListener(AudioTrack.OnRoutingChangedListener listener)
Removes an AudioTrack.OnRoutingChangedListener which has been previously added to receive rerouting notifications.
int setAuxEffectSendLevel(float level)
Sets the send level of the audio track to the attached auxiliary effect attachAuxEffect(int).
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 within the static buffer.
void setPlaybackParams(PlaybackParams params)
Sets the playback parameters.
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.
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.
int setPlaybackRate(int sampleRateInHz)
Sets the playback sample rate for this track.
int setPositionNotificationPeriod(int periodInFrames)
Sets the period for the periodic notification event.
boolean setPreferredDevice(AudioDeviceInfo deviceInfo)
Specifies an audio device (via an AudioDeviceInfo object) to route the output from this AudioTrack.
int setStereoVolume(float leftGain, float rightGain)
This method was deprecated in API level 21. Applications should use setVolume(float) instead, as it more gracefully scales down to mono, and up to multi-channel content beyond stereo.
int setVolume(float gain)
Sets the specified output gain value on all channels of this track.
void stop()
Stops playing the audio data.
int write(ByteBuffer audioData, int sizeInBytes, int writeMode)
Writes the audio data to the audio sink for playback (streaming mode), or copies audio data for later playback (static buffer mode).
int write(short[] audioData, int offsetInShorts, int sizeInShorts)
Writes the audio data to the audio sink for playback (streaming mode), or copies audio data for later playback (static buffer mode).
int write(byte[] audioData, int offsetInBytes, int sizeInBytes)
Writes the audio data to the audio sink for playback (streaming mode), or copies audio data for later playback (static buffer mode).
int write(short[] audioData, int offsetInShorts, int sizeInShorts, int writeMode)
Writes the audio data to the audio sink for playback (streaming mode), or copies audio data for later playback (static buffer mode).
int write(byte[] audioData, int offsetInBytes, int sizeInBytes, int writeMode)
Writes the audio data to the audio sink for playback (streaming mode), or copies audio data for later playback (static buffer mode).
int write(float[] audioData, int offsetInFloats, int sizeInFloats, int writeMode)
Writes the audio data to the audio sink for playback (streaming mode), or copies audio data for later playback (static buffer mode).
int write(ByteBuffer audioData, int sizeInBytes, int writeMode, long timestamp)
Writes the audio data to the audio sink for playback in streaming mode on a HW_AV_SYNC track.
Protected Methods
void finalize()
Invoked when the garbage collector has detected that this instance is no longer reachable.
int getNativeFrameCount()
This method was deprecated in API level 19. Use the identical public method getBufferSizeInFrames() instead.
void setState(int state)
This method was deprecated in API level 19. Only accessible by subclasses, which are not recommended for AudioTrack.
[Expand]
Inherited Methods
From class java.lang.Object

Constants

public static final int ERROR

Added in API level 3

Denotes a generic operation failure.

Constant Value: -1 (0xffffffff)

public static final int ERROR_BAD_VALUE

Added in 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

Added in API level 3

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

Constant Value: -3 (0xfffffffd)

public static final int MODE_STATIC

Added in 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

Added in 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

Added in API level 3

indicates AudioTrack state is paused

Constant Value: 2 (0x00000002)

public static final int PLAYSTATE_PLAYING

Added in API level 3

indicates AudioTrack state is playing

Constant Value: 3 (0x00000003)

public static final int PLAYSTATE_STOPPED

Added in API level 3

indicates AudioTrack state is stopped

Constant Value: 1 (0x00000001)

public static final int STATE_INITIALIZED

Added in 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

Added in 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

Added in API level 3

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

Constant Value: 0 (0x00000000)

public static final int SUCCESS

Added in API level 3

Denotes a successful operation.

Constant Value: 0 (0x00000000)

public static final int WRITE_BLOCKING

Added in API level 21

The write mode indicating the write operation will block until all data has been written, to be used as the actual value of the writeMode parameter in write(byte[], int, int, int), write(short[], int, int, int), write(float[], int, int, int), write(ByteBuffer, int, int), and write(ByteBuffer, int, int, long).

Constant Value: 0 (0x00000000)

public static final int WRITE_NON_BLOCKING

Added in API level 21

The write mode indicating the write operation will return immediately after queuing as much audio data for playback as possible without blocking, to be used as the actual value of the writeMode parameter in write(ByteBuffer, int, int), write(short[], int, int, int), write(float[], int, int, int), write(ByteBuffer, int, int), and write(ByteBuffer, int, int, long).

Constant Value: 1 (0x00000001)

Public Constructors

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

Added in API level 3

Class constructor.

Parameters
streamType int: the type of the audio stream. See STREAM_VOICE_CALL, STREAM_SYSTEM, STREAM_RING, STREAM_MUSIC, STREAM_ALARM, and STREAM_NOTIFICATION.
sampleRateInHz int: the initial source sample rate expressed in Hz.
channelConfig int: describes the configuration of the audio channels. See CHANNEL_OUT_MONO and CHANNEL_OUT_STEREO
audioFormat int: the format in which the audio data is represented. See ENCODING_PCM_16BIT, ENCODING_PCM_8BIT, and ENCODING_PCM_FLOAT.
bufferSizeInBytes int: the total size (in bytes) of the internal buffer where audio data is read from for playback. This should be a multiple of the frame size in bytes.

If the track's creation mode is MODE_STATIC, this is the maximum length sample, or audio clip, that can be played by this instance.

If the track's creation mode is MODE_STREAM, this should be the desired buffer size for the AudioTrack to satisfy the application's natural latency requirements. If bufferSizeInBytes is less than the minimum buffer size for the output sink, it is automatically increased to the minimum buffer size. The method getBufferSizeInFrames() returns the actual size in frames of the native buffer created, which determines the frequency to write to the streaming AudioTrack to avoid underrun.

mode int: streaming or static buffer. See MODE_STATIC and MODE_STREAM
Throws
IllegalArgumentException

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

Added in 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 retrieved by calling the getAudioSessionId() method. If a non-zero 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, otherwise a new session will be created for this track if none is supplied.

Parameters
streamType int: the type of the audio stream. See STREAM_VOICE_CALL, STREAM_SYSTEM, STREAM_RING, STREAM_MUSIC, STREAM_ALARM, and STREAM_NOTIFICATION.
sampleRateInHz int: the initial source sample rate expressed in Hz.
channelConfig int: describes the configuration of the audio channels. See CHANNEL_OUT_MONO and CHANNEL_OUT_STEREO
audioFormat int: the format in which the audio data is represented. See ENCODING_PCM_16BIT and ENCODING_PCM_8BIT, and ENCODING_PCM_FLOAT.
bufferSizeInBytes int: 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 int: streaming or static buffer. See MODE_STATIC and MODE_STREAM
sessionId int: Id of audio session the AudioTrack must be attached to
Throws
IllegalArgumentException

public AudioTrack (AudioAttributes attributes, AudioFormat format, int bufferSizeInBytes, int mode, int sessionId)

Added in API level 21

Class constructor with AudioAttributes and AudioFormat.

Parameters
attributes AudioAttributes: a non-null AudioAttributes instance.
format AudioFormat: a non-null AudioFormat instance describing the format of the data that will be played through this AudioTrack. See AudioFormat.Builder for configuring the audio format parameters such as encoding, channel mask and sample rate.
bufferSizeInBytes int: 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 int: streaming or static buffer. See MODE_STATIC and MODE_STREAM.
sessionId int: ID of audio session the AudioTrack must be attached to, or AUDIO_SESSION_ID_GENERATE if the session isn't known at construction time. See also generateAudioSessionId() to obtain a session ID before construction.
Throws
IllegalArgumentException

Public Methods

public void addOnRoutingChangedListener (AudioTrack.OnRoutingChangedListener listener, Handler handler)

Added in API level 23

Adds an AudioTrack.OnRoutingChangedListener to receive notifications of routing changes on this AudioTrack.

Parameters
listener AudioTrack.OnRoutingChangedListener: The AudioTrack.OnRoutingChangedListener interface to receive notifications of rerouting events.
handler Handler: Specifies the Handler object for the thread on which to execute the callback. If null, the Handler associated with the main Looper will be used.

public int attachAuxEffect (int effectId)

Added in 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 int: system wide unique id of the effect to attach
Returns
int error code or success, see SUCCESS, ERROR_INVALID_OPERATION, ERROR_BAD_VALUE

public void flush ()

Added in API level 3

Flushes the audio data currently queued for playback. Any data that has been written but not yet presented will be discarded. No-op if not stopped or paused, or if the track's creation mode is not MODE_STREAM.
Note that although data written but not yet presented is discarded, there is no guarantee that all of the buffer space formerly used by that data is available for a subsequent write. For example, a call to write(byte[], int, int) with sizeInBytes less than or equal to the total buffer size may return a short actual transfer count.

public int getAudioFormat ()

Added in API level 3

Returns the configured audio data encoding. See ENCODING_PCM_8BIT, ENCODING_PCM_16BIT, and ENCODING_PCM_FLOAT.

Returns
int

public int getAudioSessionId ()

Added in API level 9

Returns the audio session ID.

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

public int getBufferSizeInFrames ()

Added in API level 23

Returns the frame count of the native AudioTrack buffer.

If the track's creation mode is MODE_STATIC, it is equal to the specified bufferSizeInBytes on construction, converted to frame units. A static track's native frame count will not change.

If the track's creation mode is MODE_STREAM, it is greater than or equal to the specified bufferSizeInBytes converted to frame units. For streaming tracks, this value may be rounded up to a larger value if needed by the target output sink, and if the track is subsequently routed to a different output sink, the native frame count may enlarge to accommodate.

If the AudioTrack encoding indicates compressed data, e.g. ENCODING_AC3, then the frame count returned is the size of the native AudioTrack buffer in bytes.

See also getProperty(String) for key PROPERTY_OUTPUT_FRAMES_PER_BUFFER.

Returns
int current size in frames of the AudioTrack buffer.
Throws
IllegalStateException

public int getChannelConfiguration ()

Added in API level 3

Returns the configured channel position mask.

For example, refer to CHANNEL_OUT_MONO, CHANNEL_OUT_STEREO, CHANNEL_OUT_5POINT1. This method may return CHANNEL_INVALID if a channel index mask was used. Consider getFormat() instead, to obtain an AudioFormat, which contains both the channel position mask and the channel index mask.

Returns
int

public int getChannelCount ()

Added in API level 3

Returns the configured number of channels.

Returns
int

public AudioFormat getFormat ()

Added in API level 23

Returns the configured AudioTrack format.

Returns
AudioFormat an AudioFormat containing the AudioTrack parameters at the time of configuration.

public static float getMaxVolume ()

Added in API level 3

Returns the maximum gain value, which is greater than or equal to 1.0. Gain values greater than the maximum will be clamped to the maximum.

The word "volume" in the API name is historical; this is actually a gain. expressed as a linear multiplier on sample values, where a maximum value of 1.0 corresponds to a gain of 0 dB (sample values left unmodified).

Returns
float the maximum value, which is greater than or equal to 1.0.

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

Added in 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. For example, if you intend to dynamically set the source sample rate of an AudioTrack to a higher value than the initial source sample rate, be sure to configure the buffer size based on the highest planned sample rate.

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

public static float getMinVolume ()

Added in API level 3

Returns the minimum gain value, which is the constant 0.0. Gain values less than 0.0 will be clamped to 0.0.

The word "volume" in the API name is historical; this is actually a linear gain.

Returns
float the minimum value, which is the constant 0.0.

public static int getNativeOutputSampleRate (int streamType)

Added in API level 3

Returns the output sample rate in Hz for the specified stream type.

Parameters
streamType int
Returns
int

public int getNotificationMarkerPosition ()

Added in API level 3

Returns marker position expressed in frames.

Returns
int marker position in wrapping frame units similar to getPlaybackHeadPosition(), or zero if marker is disabled.

public int getPlayState ()

Added in API level 3

Returns the playback state of the AudioTrack instance.

Returns
int

public int getPlaybackHeadPosition ()

Added in API level 3

Returns the playback head position expressed in frames. Though the "int" type is signed 32-bits, the value should be reinterpreted as if it is unsigned 32-bits. That is, the next position after 0x7FFFFFFF is (int) 0x80000000. This is a continuously advancing counter. It will wrap (overflow) periodically, for example approximately once every 27:03:11 hours:minutes:seconds at 44.1 kHz. It is reset to zero by flush(), reloadStaticData(), and stop(). If the track's creation mode is MODE_STATIC, the return value indicates the total number of frames played since reset, not the current offset within the buffer.

Returns
int

public PlaybackParams getPlaybackParams ()

Added in API level 23

Returns the current playback parameters. See setPlaybackParams(PlaybackParams) to set playback parameters

Returns
PlaybackParams current PlaybackParams.
Throws
IllegalStateException if track is not initialized.

public int getPlaybackRate ()

Added in API level 3

Returns the current playback sample rate rate in Hz.

Returns
int

public int getPositionNotificationPeriod ()

Added in API level 3

Returns the notification update period expressed in frames. Zero means that no position update notifications are being delivered.

Returns
int

public AudioDeviceInfo getPreferredDevice ()

Added in API level 23

Returns the selected output specified by setPreferredDevice(AudioDeviceInfo). Note that this is not guaranteed to correspond to the actual device being used for playback.

Returns
AudioDeviceInfo

public AudioDeviceInfo getRoutedDevice ()

Added in API level 23

Returns an AudioDeviceInfo identifying the current routing of this AudioTrack. Note: The query is only valid if the AudioTrack is currently playing. If it is not, getRoutedDevice() will return null.

Returns
AudioDeviceInfo

public int getSampleRate ()

Added in API level 3

Returns the configured audio data sample rate in Hz

Returns
int

public int getState ()

Added in 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 resources have been acquired.

Returns
int

public int getStreamType ()

Added in 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, STREAM_ALARM, STREAM_NOTIFICATION, or STREAM_DTMF.

Returns
int

public boolean getTimestamp (AudioTimestamp timestamp)

Added in API level 19

Poll for a timestamp on demand.

If you need to track timestamps during initial warmup or after a routing or mode change, you should request a new timestamp periodically until the reported timestamps show that the frame position is advancing, or until it becomes clear that timestamps are unavailable for this route.

After the clock is advancing at a stable rate, query for a new timestamp approximately once every 10 seconds to once per minute. Calling this method more often is inefficient. It is also counter-productive to call this method more often than recommended, because the short-term differences between successive timestamp reports are not meaningful. If you need a high-resolution mapping between frame position and presentation time, consider implementing that at application level, based on low-resolution timestamps.

The audio data at the returned position may either already have been presented, or may have not yet been presented but is committed to be presented. It is not possible to request the time corresponding to a particular position, or to request the (fractional) position corresponding to a particular time. If you need such features, consider implementing them at application level.

Parameters
timestamp AudioTimestamp: a reference to a non-null AudioTimestamp instance allocated and owned by caller.
Returns
boolean true if a timestamp is available, or false if no timestamp is available. If a timestamp if available, the AudioTimestamp instance is filled in with a position in frame units, together with the estimated time when that frame was presented or is committed to be presented. In the case that no timestamp is available, any supplied instance is left unaltered. A timestamp may be temporarily unavailable while the audio clock is stabilizing, or during and immediately after a route change. A timestamp is permanently unavailable for a given route if the route does not support timestamps. In this case, the approximate frame position can be obtained using getPlaybackHeadPosition(). However, it may be useful to continue to query for timestamps occasionally, to recover after a route change.

public void pause ()

Added in API level 3

Pauses the playback of the audio data. Data that has not been played back will not be discarded. Subsequent calls to play() will play this data back. See flush() to discard this data.

Throws
IllegalStateException

public void play ()

Added in API level 3

Starts playing an AudioTrack.

If track's creation mode is MODE_STATIC, you must have called one of the write methods (write(byte[], int, int), write(byte[], int, int, int), write(short[], int, int), write(short[], int, int, int), write(float[], int, int, int), or write(ByteBuffer, int, int)) prior to play().

If the mode is MODE_STREAM, you can optionally prime the data path prior to calling play(), by writing up to bufferSizeInBytes (from constructor). If you don't call write() first, or if you call write() but with an insufficient amount of data, then the track will be in underrun state at play(). In this case, playback will not actually start playing until the data path is filled to a device-specific minimum level. This requirement for the path to be filled to a minimum level is also true when resuming audio playback after calling stop(). Similarly the buffer will need to be filled up again after the track underruns due to failure to call write() in a timely manner with sufficient data. For portability, an application should prime the data path to the maximum allowed by writing data until the write() method returns a short transfer count. This allows play() to start immediately, and reduces the chance of underrun.

Throws
IllegalStateException if the track isn't properly initialized

public void release ()

Added in API level 3

Releases the native AudioTrack resources.

public int reloadStaticData ()

Added in API level 3

Sets the playback head position within the static buffer to zero, that is it rewinds to start of static buffer. The track must be stopped or paused, and the track's creation mode must be MODE_STATIC.

As of M, also resets the value returned by getPlaybackHeadPosition() to zero. For earlier API levels, the reset behavior is unspecified.

Use setPlaybackHeadPosition(int) with a zero position if the reset of getPlaybackHeadPosition() is not needed.

Returns
int error code or success, see SUCCESS, ERROR_BAD_VALUE, ERROR_INVALID_OPERATION

public void removeOnRoutingChangedListener (AudioTrack.OnRoutingChangedListener listener)

Added in API level 23

Removes an AudioTrack.OnRoutingChangedListener which has been previously added to receive rerouting notifications.

Parameters
listener AudioTrack.OnRoutingChangedListener: The previously added AudioTrack.OnRoutingChangedListener interface to remove.

public int setAuxEffectSendLevel (float level)

Added in API level 9

Sets the send level of the audio track to the attached auxiliary effect attachAuxEffect(int). Effect levels are clamped to the closed interval [0.0, max] where max is the value of getMaxVolume(). A value of 0.0 results in no effect, and a value of 1.0 is full send.

By default the send level is 0.0f, 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 linear scalar. UI controls should be scaled logarithmically: the gain applied by audio framework ranges from -72dB to at least 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 float: linear send level
Returns
int error code or success, see SUCCESS, ERROR_INVALID_OPERATION, ERROR

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

Added in API level 3

Sets the loop points and the loop count. The loop can be infinite. Similarly to setPlaybackHeadPosition, the track must be stopped or paused for the loop points to be changed, and must use the MODE_STATIC mode.

Parameters
startInFrames int: loop start marker expressed in frames. Zero corresponds to start of buffer. The start marker must not be greater than or equal to the buffer size in frames, or negative.
endInFrames int: loop end marker expressed in frames. The total buffer size in frames corresponds to end of buffer. The end marker must not be greater than the buffer size in frames. For looping, the end marker must not be less than or equal to the start marker, but to disable looping it is permitted for start marker, end marker, and loop count to all be 0. If any input parameters are out of range, this method returns ERROR_BAD_VALUE. If the loop period (endInFrames - startInFrames) is too small for the implementation to support, ERROR_BAD_VALUE is returned. The loop range is the interval [startInFrames, endInFrames).
As of M, the position is left unchanged, unless it is greater than or equal to the loop end marker, in which case it is forced to the loop start marker. For earlier API levels, the effect on position is unspecified.
loopCount int: the number of times the loop is looped; must be greater than or equal to -1. A value of -1 means infinite looping, and 0 disables looping. A value of positive N means to "loop" (go back) N times. For example, a value of one means to play the region two times in total.
Returns
int error code or success, see SUCCESS, ERROR_BAD_VALUE, ERROR_INVALID_OPERATION

public int setNotificationMarkerPosition (int markerInFrames)

Added in API level 3

Sets the position of the notification marker. At most one marker can be active.

Parameters
markerInFrames int: marker position in wrapping frame units similar to getPlaybackHeadPosition(), or zero to disable the marker. To set a marker at a position which would appear as zero due to wraparound, a workaround is to use a non-zero position near zero, such as -1 or 1.
Returns
int error code or success, see SUCCESS, ERROR_BAD_VALUE, ERROR_INVALID_OPERATION

public int setPlaybackHeadPosition (int positionInFrames)

Added in API level 3

Sets the playback head position within the static buffer. The track must be stopped or paused for the position to be changed, and must use the MODE_STATIC mode.

Parameters
positionInFrames int: playback head position within buffer, expressed in frames. Zero corresponds to start of buffer. The position must not be greater than the buffer size in frames, or negative. Though this method and getPlaybackHeadPosition() have similar names, the position values have different meanings.
If looping is currently enabled and the new position is greater than or equal to the loop end marker, the behavior varies by API level: as of M, the looping is first disabled and then the position is set. For earlier API levels, the behavior is unspecified.
Returns
int error code or success, see SUCCESS, ERROR_BAD_VALUE, ERROR_INVALID_OPERATION

public void setPlaybackParams (PlaybackParams params)

Added in API level 23

Sets the playback parameters. This method returns failure if it cannot apply the playback parameters. One possible cause is that the parameters for speed or pitch are out of range. Another possible cause is that the AudioTrack is streaming (see MODE_STREAM) and the buffer size is too small. For speeds greater than 1.0f, the AudioTrack buffer on configuration must be larger than the speed multiplied by the minimum size getMinBufferSize(int, int, int)) to allow proper playback.

Parameters
params PlaybackParams: see PlaybackParams. In particular, speed, pitch, and audio mode should be set.
Throws
IllegalArgumentException if the parameters are invalid or not accepted.
IllegalStateException if track is not initialized.

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

Added in 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 Handler: the Handler that will receive the event notification messages.

public void setPlaybackPositionUpdateListener (AudioTrack.OnPlaybackPositionUpdateListener listener)

Added in 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 int setPlaybackRate (int sampleRateInHz)

Added in 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 (as set by the sampleRateInHz parameter in the AudioTrack(int, int, int, int, int, int) constructor), not the original sampling rate of the content. For example, 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 pitch shift down by one octave. The valid sample rate range is from 1 Hz to twice the value returned by getNativeOutputSampleRate(int). Use setPlaybackParams(PlaybackParams) for speed control.

This method may also be used to repurpose an existing AudioTrack for playback of content of differing sample rate, but with identical encoding and channel mask.

Parameters
sampleRateInHz int: the sample rate expressed in Hz
Returns
int error code or success, see SUCCESS, ERROR_BAD_VALUE, ERROR_INVALID_OPERATION

public int setPositionNotificationPeriod (int periodInFrames)

Added in API level 3

Sets the period for the periodic notification event.

Parameters
periodInFrames int: update period expressed in frames. Zero period means no position updates. A negative period is not allowed.
Returns
int error code or success, see SUCCESS, ERROR_INVALID_OPERATION

public boolean setPreferredDevice (AudioDeviceInfo deviceInfo)

Added in API level 23

Specifies an audio device (via an AudioDeviceInfo object) to route the output from this AudioTrack.

Parameters
deviceInfo AudioDeviceInfo: The AudioDeviceInfo specifying the audio sink. If deviceInfo is null, default routing is restored.
Returns
boolean true if succesful, false if the specified AudioDeviceInfo is non-null and does not correspond to a valid audio output device.

public int setStereoVolume (float leftGain, float rightGain)

Added in API level 3

This method was deprecated in API level 21.
Applications should use setVolume(float) instead, as it more gracefully scales down to mono, and up to multi-channel content beyond stereo.

Sets the specified left and right output gain values on the AudioTrack.

Gain values are clamped to the closed interval [0.0, max] where max is the value of getMaxVolume(). A value of 0.0 results in zero gain (silence), and a value of 1.0 means unity gain (signal unchanged). The default value is 1.0 meaning unity gain.

The word "volume" in the API name is historical; this is actually a linear gain.

Parameters
leftGain float: output gain for the left channel.
rightGain float: output gain for the right channel
Returns
int error code or success, see SUCCESS, ERROR_INVALID_OPERATION

public int setVolume (float gain)

Added in API level 21

Sets the specified output gain value on all channels of this track.

Gain values are clamped to the closed interval [0.0, max] where max is the value of getMaxVolume(). A value of 0.0 results in zero gain (silence), and a value of 1.0 means unity gain (signal unchanged). The default value is 1.0 meaning unity gain.

This API is preferred over setStereoVolume(float, float), as it more gracefully scales down to mono, and up to multi-channel content beyond stereo.

The word "volume" in the API name is historical; this is actually a linear gain.

Parameters
gain float: output gain for all channels.
Returns
int error code or success, see SUCCESS, ERROR_INVALID_OPERATION

public void stop ()

Added in API level 3

Stops playing the audio data. When used on an instance created in MODE_STREAM mode, audio will stop playing after the last buffer that was written has been played. For an immediate stop, use pause(), followed by flush() to discard audio data that hasn't been played back yet.

Throws
IllegalStateException

public int write (ByteBuffer audioData, int sizeInBytes, int writeMode)

Added in API level 21

Writes the audio data to the audio sink for playback (streaming mode), or copies audio data for later playback (static buffer mode). The audioData in ByteBuffer should match the format specified in the AudioTrack constructor.

In streaming mode, the blocking behavior depends on the write mode. If the write mode is WRITE_BLOCKING, the write will normally block until all the data has been enqueued for playback, and will return a full transfer count. However, if the write mode is WRITE_NON_BLOCKING, or the track is stopped or paused on entry, or another thread interrupts the write by calling stop or pause, or an I/O error occurs during the write, then the write may return a short transfer count.

In static buffer mode, copies the data to the buffer starting at offset 0, and the write mode is ignored. Note that the actual playback of this data might occur after this function returns.

Parameters
audioData ByteBuffer: the buffer that holds the data to play, starting at the position reported by audioData.position().
Note that upon return, the buffer position (audioData.position()) will have been advanced to reflect the amount of data that was successfully written to the AudioTrack.
sizeInBytes int: number of bytes to write.
Note this may differ from audioData.remaining(), but cannot exceed it.
writeMode int: one of WRITE_BLOCKING, WRITE_NON_BLOCKING. It has no effect in static mode.
With WRITE_BLOCKING, the write will block until all data has been written to the audio sink.
With WRITE_NON_BLOCKING, the write will return immediately after queuing as much audio data for playback as possible without blocking.
Returns
int zero or the positive number of bytes that were written, or ERROR_BAD_VALUE, ERROR_INVALID_OPERATION, or ERROR_DEAD_OBJECT if the AudioTrack is not valid anymore and needs to be recreated. The dead object error code is not returned if some data was successfully transferred. In this case, the error is returned at the next write().

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

Added in API level 3

Writes the audio data to the audio sink for playback (streaming mode), or copies audio data for later playback (static buffer mode). The format specified in the AudioTrack constructor should be ENCODING_PCM_16BIT to correspond to the data in the array.

In streaming mode, the write will normally block until all the data has been enqueued for playback, and will return a full transfer count. However, if the track is stopped or paused on entry, or another thread interrupts the write by calling stop or pause, or an I/O error occurs during the write, then the write may return a short transfer count.

In static buffer mode, copies the data to the buffer starting at offset 0. Note that the actual playback of this data might occur after this function returns.

Parameters
audioData short: the array that holds the data to play.
offsetInShorts int: the offset expressed in shorts in audioData where the data to play starts.
sizeInShorts int: the number of shorts to read in audioData after the offset.
Returns
int zero or the positive number of shorts that were written, or ERROR_INVALID_OPERATION if the track isn't properly initialized, or ERROR_BAD_VALUE if the parameters don't resolve to valid data and indexes, or ERROR_DEAD_OBJECT if the AudioTrack is not valid anymore and needs to be recreated. The dead object error code is not returned if some data was successfully transferred. In this case, the error is returned at the next write(). This is equivalent to write(short[], int, int, int) with writeMode set to WRITE_BLOCKING.

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

Added in API level 3

Writes the audio data to the audio sink for playback (streaming mode), or copies audio data for later playback (static buffer mode). The format specified in the AudioTrack constructor should be ENCODING_PCM_8BIT to correspond to the data in the array.

In streaming mode, the write will normally block until all the data has been enqueued for playback, and will return a full transfer count. However, if the track is stopped or paused on entry, or another thread interrupts the write by calling stop or pause, or an I/O error occurs during the write, then the write may return a short transfer count.

In static buffer mode, copies the data to the buffer starting at offset 0. Note that the actual playback of this data might occur after this function returns.

Parameters
audioData byte: the array that holds the data to play.
offsetInBytes int: the offset expressed in bytes in audioData where the data to play starts.
sizeInBytes int: the number of bytes to read in audioData after the offset.
Returns
int zero or the positive number of bytes that were written, or ERROR_INVALID_OPERATION if the track isn't properly initialized, or ERROR_BAD_VALUE if the parameters don't resolve to valid data and indexes, or ERROR_DEAD_OBJECT if the AudioTrack is not valid anymore and needs to be recreated. The dead object error code is not returned if some data was successfully transferred. In this case, the error is returned at the next write(). This is equivalent to write(byte[], int, int, int) with writeMode set to WRITE_BLOCKING.

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

Added in API level 23

Writes the audio data to the audio sink for playback (streaming mode), or copies audio data for later playback (static buffer mode). The format specified in the AudioTrack constructor should be ENCODING_PCM_16BIT to correspond to the data in the array.

In streaming mode, the blocking behavior depends on the write mode. If the write mode is WRITE_BLOCKING, the write will normally block until all the data has been enqueued for playback, and will return a full transfer count. However, if the write mode is WRITE_NON_BLOCKING, or the track is stopped or paused on entry, or another thread interrupts the write by calling stop or pause, or an I/O error occurs during the write, then the write may return a short transfer count.

In static buffer mode, copies the data to the buffer starting at offset 0. Note that the actual playback of this data might occur after this function returns.

Parameters
audioData short: the array that holds the data to play.
offsetInShorts int: the offset expressed in shorts in audioData where the data to play starts.
sizeInShorts int: the number of shorts to read in audioData after the offset.
writeMode int: one of WRITE_BLOCKING, WRITE_NON_BLOCKING. It has no effect in static mode.
With WRITE_BLOCKING, the write will block until all data has been written to the audio sink.
With WRITE_NON_BLOCKING, the write will return immediately after queuing as much audio data for playback as possible without blocking.
Returns
int zero or the positive number of shorts that were written, or ERROR_INVALID_OPERATION if the track isn't properly initialized, or ERROR_BAD_VALUE if the parameters don't resolve to valid data and indexes, or ERROR_DEAD_OBJECT if the AudioTrack is not valid anymore and needs to be recreated. The dead object error code is not returned if some data was successfully transferred. In this case, the error is returned at the next write().

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

Added in API level 23

Writes the audio data to the audio sink for playback (streaming mode), or copies audio data for later playback (static buffer mode). The format specified in the AudioTrack constructor should be ENCODING_PCM_8BIT to correspond to the data in the array.

In streaming mode, the blocking behavior depends on the write mode. If the write mode is WRITE_BLOCKING, the write will normally block until all the data has been enqueued for playback, and will return a full transfer count. However, if the write mode is WRITE_NON_BLOCKING, or the track is stopped or paused on entry, or another thread interrupts the write by calling stop or pause, or an I/O error occurs during the write, then the write may return a short transfer count.

In static buffer mode, copies the data to the buffer starting at offset 0, and the write mode is ignored. Note that the actual playback of this data might occur after this function returns.

Parameters
audioData byte: the array that holds the data to play.
offsetInBytes int: the offset expressed in bytes in audioData where the data to play starts.
sizeInBytes int: the number of bytes to read in audioData after the offset.
writeMode int: one of WRITE_BLOCKING, WRITE_NON_BLOCKING. It has no effect in static mode.
With WRITE_BLOCKING, the write will block until all data has been written to the audio sink.
With WRITE_NON_BLOCKING, the write will return immediately after queuing as much audio data for playback as possible without blocking.
Returns
int zero or the positive number of bytes that were written, or ERROR_INVALID_OPERATION if the track isn't properly initialized, or ERROR_BAD_VALUE if the parameters don't resolve to valid data and indexes, or ERROR_DEAD_OBJECT if the AudioTrack is not valid anymore and needs to be recreated. The dead object error code is not returned if some data was successfully transferred. In this case, the error is returned at the next write().

public int write (float[] audioData, int offsetInFloats, int sizeInFloats, int writeMode)

Added in API level 21

Writes the audio data to the audio sink for playback (streaming mode), or copies audio data for later playback (static buffer mode). The format specified in the AudioTrack constructor should be ENCODING_PCM_FLOAT to correspond to the data in the array.

In streaming mode, the blocking behavior depends on the write mode. If the write mode is WRITE_BLOCKING, the write will normally block until all the data has been enqueued for playback, and will return a full transfer count. However, if the write mode is WRITE_NON_BLOCKING, or the track is stopped or paused on entry, or another thread interrupts the write by calling stop or pause, or an I/O error occurs during the write, then the write may return a short transfer count.

In static buffer mode, copies the data to the buffer starting at offset 0, and the write mode is ignored. Note that the actual playback of this data might occur after this function returns.

Parameters
audioData float: the array that holds the data to play. The implementation does not clip for sample values within the nominal range [-1.0f, 1.0f], provided that all gains in the audio pipeline are less than or equal to unity (1.0f), and in the absence of post-processing effects that could add energy, such as reverb. For the convenience of applications that compute samples using filters with non-unity gain, sample values +3 dB beyond the nominal range are permitted. However such values may eventually be limited or clipped, depending on various gains and later processing in the audio path. Therefore applications are encouraged to provide samples values within the nominal range.
offsetInFloats int: the offset, expressed as a number of floats, in audioData where the data to play starts.
sizeInFloats int: the number of floats to read in audioData after the offset.
writeMode int: one of WRITE_BLOCKING, WRITE_NON_BLOCKING. It has no effect in static mode.
With WRITE_BLOCKING, the write will block until all data has been written to the audio sink.
With WRITE_NON_BLOCKING, the write will return immediately after queuing as much audio data for playback as possible without blocking.
Returns
int zero or the positive number of floats that were written, or ERROR_INVALID_OPERATION if the track isn't properly initialized, or ERROR_BAD_VALUE if the parameters don't resolve to valid data and indexes, or ERROR_DEAD_OBJECT if the AudioTrack is not valid anymore and needs to be recreated. The dead object error code is not returned if some data was successfully transferred. In this case, the error is returned at the next write().

public int write (ByteBuffer audioData, int sizeInBytes, int writeMode, long timestamp)

Added in API level 23

Writes the audio data to the audio sink for playback in streaming mode on a HW_AV_SYNC track. The blocking behavior will depend on the write mode.

Parameters
audioData ByteBuffer: the buffer that holds the data to play, starting at the position reported by audioData.position().
Note that upon return, the buffer position (audioData.position()) will have been advanced to reflect the amount of data that was successfully written to the AudioTrack.
sizeInBytes int: number of bytes to write.
Note this may differ from audioData.remaining(), but cannot exceed it.
writeMode int: one of WRITE_BLOCKING, WRITE_NON_BLOCKING.
With WRITE_BLOCKING, the write will block until all data has been written to the audio sink.
With WRITE_NON_BLOCKING, the write will return immediately after queuing as much audio data for playback as possible without blocking.
timestamp long: The timestamp of the first decodable audio frame in the provided audioData.
Returns
int zero or a positive number of bytes that were written, or ERROR_BAD_VALUE, ERROR_INVALID_OPERATION, or ERROR_DEAD_OBJECT if the AudioTrack is not valid anymore and needs to be recreated. The dead object error code is not returned if some data was successfully transferred. In this case, the error is returned at the next write().

Protected Methods

protected void finalize ()

Added in API level 3

Invoked when the garbage collector has detected that this instance is no longer reachable. The default implementation does nothing, but this method can be overridden to free resources.

Note that objects that override finalize are significantly more expensive than objects that don't. Finalizers may be run a long time after the object is no longer reachable, depending on memory pressure, so it's a bad idea to rely on them for cleanup. Note also that finalizers are run on a single VM-wide finalizer thread, so doing blocking work in a finalizer is a bad idea. A finalizer is usually only necessary for a class that has a native peer and needs to call a native method to destroy that peer. Even then, it's better to provide an explicit close method (and implement Closeable), and insist that callers manually dispose of instances. This works well for something like files, but less well for something like a BigInteger where typical calling code would have to deal with lots of temporaries. Unfortunately, code that creates lots of temporaries is the worst kind of code from the point of view of the single finalizer thread.

If you must use finalizers, consider at least providing your own ReferenceQueue and having your own thread process that queue.

Unlike constructors, finalizers are not automatically chained. You are responsible for calling super.finalize() yourself.

Uncaught exceptions thrown by finalizers are ignored and do not terminate the finalizer thread. See Effective Java Item 7, "Avoid finalizers" for more.

protected int getNativeFrameCount ()

Added in API level 3

This method was deprecated in API level 19.
Use the identical public method getBufferSizeInFrames() instead.

Returns the frame count of the native AudioTrack buffer.

Returns
int current size in frames of the AudioTrack buffer.
Throws
IllegalStateException

protected void setState (int state)

Added in API level 3

This method was deprecated in API level 19.
Only accessible by subclasses, which are not recommended for AudioTrack.

Sets the initialization state of the instance. This method was originally intended to be used in an AudioTrack subclass constructor to set a subclass-specific post-initialization state. However, subclasses of AudioTrack are no longer recommended, so this method is obsolete.

Parameters
state int: the state of the AudioTrack instance