public final class AudioTrack
extends java.lang.Object
AudioTrack and handles
playback position smoothing, non-blocking writes and reconfiguration.
Before starting playback, specify the input format by calling
configure(String, int, int, int, int). Optionally call setAudioSessionId(int),
setStreamType(int), enableTunnelingV21(int) and disableTunneling()
to configure audio playback. These methods may be called after writing data to the track, in
which case it will be reinitialized as required.
Call handleBuffer(ByteBuffer, long) to write data, and handleDiscontinuity()
when the data being fed is discontinuous. Call play() to start playing the written data.
Call configure(String, int, int, int, int) whenever the input format changes. The track
will be reinitialized on the next call to handleBuffer(ByteBuffer, long).
Calling reset() releases the underlying AudioTrack (and so does
calling configure(String, int, int, int, int) unless the format is unchanged). It is
safe to call handleBuffer(ByteBuffer, long) after reset() without calling
configure(String, int, int, int, int).
Call playToEndOfStream() repeatedly to play out all data when no more input buffers will
be provided via handleBuffer(ByteBuffer, long) until the next reset(). Call
release() when the instance is no longer required.
| Modifier and Type | Class and Description |
|---|---|
static class |
AudioTrack.ConfigurationException
Thrown when a failure occurs configuring the track.
|
static class |
AudioTrack.InitializationException
Thrown when a failure occurs initializing an
AudioTrack. |
static class |
AudioTrack.InvalidAudioTrackTimestampException
Thrown when
AudioTrack.getTimestamp(android.media.AudioTimestamp) returns a spurious timestamp, if
AudioTrack#failOnSpuriousAudioTimestamp is set. |
static interface |
AudioTrack.Listener
Listener for audio track events.
|
static class |
AudioTrack.WriteException
Thrown when a failure occurs writing to an
AudioTrack. |
| Modifier and Type | Field and Description |
|---|---|
static long |
CURRENT_POSITION_NOT_SET
Returned by
getCurrentPositionUs(boolean) when the position is not set. |
static boolean |
enablePreV21AudioSessionWorkaround
Whether to enable a workaround for an issue where an audio effect does not keep its session
active across releasing/initializing a new audio track, on platform builds where
Util.SDK_INT < 21. |
static boolean |
failOnSpuriousAudioTimestamp
Whether to throw an
AudioTrack.InvalidAudioTrackTimestampException when a spurious timestamp is
reported from AudioTrack.getTimestamp(android.media.AudioTimestamp). |
| Constructor and Description |
|---|
AudioTrack(AudioCapabilities audioCapabilities,
AudioProcessor[] audioProcessors,
AudioTrack.Listener listener) |
| Modifier and Type | Method and Description |
|---|---|
void |
configure(java.lang.String mimeType,
int channelCount,
int sampleRate,
int pcmEncoding,
int specifiedBufferSize)
Configures (or reconfigures) the audio track.
|
void |
configure(java.lang.String mimeType,
int channelCount,
int sampleRate,
int pcmEncoding,
int specifiedBufferSize,
int[] outputChannels)
Configures (or reconfigures) the audio track.
|
void |
disableTunneling()
Disables tunneling.
|
void |
enableTunnelingV21(int tunnelingAudioSessionId)
Enables tunneling.
|
long |
getCurrentPositionUs(boolean sourceEnded)
Returns the playback position in the stream starting at zero, in microseconds, or
CURRENT_POSITION_NOT_SET if it is not yet available. |
PlaybackParameters |
getPlaybackParameters()
Gets the
PlaybackParameters. |
boolean |
handleBuffer(java.nio.ByteBuffer buffer,
long presentationTimeUs)
Attempts to process data from a
ByteBuffer, starting from its current position and
ending at its limit (exclusive). |
void |
handleDiscontinuity()
Signals to the audio track that the next buffer is discontinuous with the previous buffer.
|
boolean |
hasPendingData()
Returns whether the audio track has more data pending that will be played back.
|
boolean |
isEnded()
Returns whether all buffers passed to
handleBuffer(ByteBuffer, long) have been
completely processed and played. |
boolean |
isPassthroughSupported(java.lang.String mimeType)
Returns whether it's possible to play audio in the specified format using encoded passthrough.
|
void |
pause()
Pauses playback.
|
void |
play()
Starts or resumes playing audio if the audio track has been initialized.
|
void |
playToEndOfStream()
Plays out remaining audio.
|
void |
release()
Releases all resources associated with this instance.
|
void |
reset()
Releases the underlying audio track asynchronously.
|
void |
setAudioSessionId(int audioSessionId)
Sets the audio session id.
|
PlaybackParameters |
setPlaybackParameters(PlaybackParameters playbackParameters)
Attempts to set the playback parameters and returns the active playback parameters, which may
differ from those passed in.
|
void |
setStreamType(int streamType)
Sets the stream type for audio track.
|
void |
setVolume(float volume)
Sets the playback volume.
|
public static final long CURRENT_POSITION_NOT_SET
getCurrentPositionUs(boolean) when the position is not set.public static boolean enablePreV21AudioSessionWorkaround
Util.SDK_INT < 21.
The flag must be set before creating a player.
public static boolean failOnSpuriousAudioTimestamp
AudioTrack.InvalidAudioTrackTimestampException when a spurious timestamp is
reported from AudioTrack.getTimestamp(android.media.AudioTimestamp).
The flag must be set before creating a player. Should be set to true for testing and
debugging purposes only.
public AudioTrack(AudioCapabilities audioCapabilities, AudioProcessor[] audioProcessors, AudioTrack.Listener listener)
audioCapabilities - The audio capabilities for playback on this device. May be null if the
default capabilities (no encoded audio passthrough support) should be assumed.audioProcessors - An array of AudioProcessors that will process PCM audio before
output. May be empty.listener - Listener for audio track events.public boolean isPassthroughSupported(java.lang.String mimeType)
mimeType - The format mime type.public long getCurrentPositionUs(boolean sourceEnded)
CURRENT_POSITION_NOT_SET if it is not yet available.
If the device supports it, the method uses the playback timestamp from
AudioTrack.getTimestamp(android.media.AudioTimestamp). Otherwise, it derives a smoothed position by
sampling the AudioTrack's frame position.
sourceEnded - Specify true if no more input buffers will be provided.public void configure(java.lang.String mimeType,
int channelCount,
int sampleRate,
int pcmEncoding,
int specifiedBufferSize)
throws AudioTrack.ConfigurationException
mimeType - The mime type.channelCount - The number of channels.sampleRate - The sample rate in Hz.pcmEncoding - For PCM formats, the encoding used. One of C.ENCODING_PCM_16BIT,
C.ENCODING_PCM_16BIT, C.ENCODING_PCM_24BIT and
C.ENCODING_PCM_32BIT.specifiedBufferSize - A specific size for the playback buffer in bytes, or 0 to infer a
suitable buffer size automatically.AudioTrack.ConfigurationException - If an error occurs configuring the track.public void configure(java.lang.String mimeType,
int channelCount,
int sampleRate,
int pcmEncoding,
int specifiedBufferSize,
int[] outputChannels)
throws AudioTrack.ConfigurationException
mimeType - The mime type.channelCount - The number of channels.sampleRate - The sample rate in Hz.pcmEncoding - For PCM formats, the encoding used. One of C.ENCODING_PCM_16BIT,
C.ENCODING_PCM_16BIT, C.ENCODING_PCM_24BIT and
C.ENCODING_PCM_32BIT.specifiedBufferSize - A specific size for the playback buffer in bytes, or 0 to infer a
suitable buffer size automatically.outputChannels - A mapping from input to output channels that is applied to this track's
input as a preprocessing step, if handling PCM input. Specify null to leave the
input unchanged. Otherwise, the element at index i specifies index of the input
channel to map to output channel i when preprocessing input buffers. After the
map is applied the audio data will have outputChannels.length channels.AudioTrack.ConfigurationException - If an error occurs configuring the track.public void play()
public void handleDiscontinuity()
public boolean handleBuffer(java.nio.ByteBuffer buffer,
long presentationTimeUs)
throws AudioTrack.InitializationException,
AudioTrack.WriteException
ByteBuffer, starting from its current position and
ending at its limit (exclusive). The position of the ByteBuffer is advanced by the
number of bytes that were handled. AudioTrack.Listener.onPositionDiscontinuity() will be called if
presentationTimeUs is discontinuous with the last buffer handled since the last reset.
Returns whether the data was handled in full. If the data was not handled in full then the same
ByteBuffer must be provided to subsequent calls until it has been fully consumed,
except in the case of an interleaving call to reset() (or an interleaving call to
configure(String, int, int, int, int) that caused the track to be reset).
buffer - The buffer containing audio data.presentationTimeUs - The presentation timestamp of the buffer in microseconds.AudioTrack.InitializationException - If an error occurs initializing the track.AudioTrack.WriteException - If an error occurs writing the audio data.public void playToEndOfStream()
throws AudioTrack.WriteException
isEnded() will return true when playback has ended.AudioTrack.WriteException - If an error occurs draining data to the track.public boolean isEnded()
handleBuffer(ByteBuffer, long) have been
completely processed and played.public boolean hasPendingData()
public PlaybackParameters setPlaybackParameters(PlaybackParameters playbackParameters)
playbackParameters - The new playback parameters to attempt to set.public PlaybackParameters getPlaybackParameters()
PlaybackParameters.public void setStreamType(int streamType)
If the audio track is configured for use with tunneling then the stream type is ignored, the audio track is not reset and the audio session id is not cleared. The passed stream type will be used if the audio track is later re-configured into non-tunneled mode.
streamType - The C.StreamType to use for audio output.public void setAudioSessionId(int audioSessionId)
public void enableTunnelingV21(int tunnelingAudioSessionId)
If this instance has AudioProcessors and tunneling is enabled, care must be taken that
audio processors do not output buffers with a different duration than their input, and buffer
processors must produce output corresponding to their last input immediately after that input
is queued.
tunnelingAudioSessionId - The audio session id to use.java.lang.IllegalStateException - Thrown if enabling tunneling on platform API version < 21.public void disableTunneling()
public void setVolume(float volume)
volume - A volume in the range [0.0, 1.0].public void pause()
public void reset()
Calling handleBuffer(ByteBuffer, long) will block until the audio track has been
released, so it is safe to use the audio track immediately after a reset. The audio session may
remain active until release() is called.
public void release()