java.lang.Object | |
↳ | android.media.AudioTrack |
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)
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:
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.
Nested Classes | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
|
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 | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
|
Class constructor.
|
||||||||||
|
Class constructor with audio session.
|
Public Methods | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
|
Attaches an auxiliary effect to the audio track.
|
||||||||||
|
Flushes the audio data currently queued for playback.
|
||||||||||
|
Returns the configured audio data format.
|
||||||||||
|
Returns the audio session ID.
|
||||||||||
|
Returns the configured channel configuration.
|
||||||||||
|
Returns the configured number of channels.
|
||||||||||
|
Returns the maximum valid volume value.
|
||||||||||
|
Returns the minimum buffer size required for the successful creation of an AudioTrack
object to be created in the
MODE_STREAM
mode.
|
||||||||||
|
Returns the minimum valid volume value.
|
||||||||||
|
Returns the output sample rate in Hz for the specified stream type.
|
||||||||||
|
Returns marker position expressed in frames.
|
||||||||||
|
Returns the playback state of the AudioTrack instance.
|
||||||||||
|
Returns the playback head position expressed in frames.
|
||||||||||
|
Returns the current playback rate in Hz.
|
||||||||||
|
Returns the notification update period expressed in frames.
|
||||||||||
|
Returns the configured audio data sample rate in Hz
|
||||||||||
|
Returns the state of the AudioTrack instance.
|
||||||||||
|
Returns the type of audio stream this AudioTrack is configured for.
|
||||||||||
|
Poll for a timestamp on demand.
|
||||||||||
|
Pauses the playback of the audio data.
|
||||||||||
|
Starts playing an AudioTrack.
|
||||||||||
|
Releases the native AudioTrack resources.
|
||||||||||
|
Notifies the native resource to reuse the audio data already loaded in the native
layer, that is to rewind to start of buffer.
|
||||||||||
|
Sets the send level of the audio track to the attached auxiliary effect
attachAuxEffect(int)
.
|
||||||||||
|
Sets the loop points and the loop count.
|
||||||||||
|
Sets the position of the notification marker.
|
||||||||||
|
Sets the playback head position.
|
||||||||||
|
Sets the listener the AudioTrack notifies when a previously set marker is reached or
for each periodic playback head position update.
|
||||||||||
|
Sets the listener the AudioTrack notifies when a previously set marker is reached or
for each periodic playback head position update.
|
||||||||||
|
Sets the playback sample rate for this track.
|
||||||||||
|
Sets the period for the periodic notification event.
|
||||||||||
|
Sets the specified left/right output volume values on the AudioTrack.
|
||||||||||
|
Stops playing the audio data.
|
||||||||||
|
Writes the audio data to the audio sink for playback (streaming mode),
or copies audio data for later playback (static buffer mode).
|
||||||||||
|
Writes the audio data to the audio sink for playback (streaming mode),
or copies audio data for later playback (static buffer mode).
|
Protected Methods | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
|
Invoked when the garbage collector has detected that this instance is no longer reachable.
|
||||||||||
|
This method was deprecated
in API level 19.
Only accessible by subclasses, which are not recommended for AudioTrack.
See
getProperty(String)
for key
PROPERTY_OUTPUT_FRAMES_PER_BUFFER
.
|
||||||||||
|
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
|
Denotes a generic operation failure.
Denotes a failure due to the use of an invalid value.
Denotes a failure due to the improper use of a method.
Creation mode where audio data is transferred from Java to the native layer only once before the audio starts playing.
Creation mode where audio data is streamed from Java to the native layer as the audio is playing.
indicates AudioTrack state is paused
indicates AudioTrack state is playing
indicates AudioTrack state is stopped
State of an AudioTrack that is ready to be used.
State of a successfully initialized AudioTrack that uses static data, but that hasn't received that data yet.
State of an AudioTrack that was not successfully initialized upon creation.
Denotes a successful operation.
Class constructor.
streamType |
the type of the audio stream. See
STREAM_VOICE_CALL
,
STREAM_SYSTEM
,
STREAM_RING
,
STREAM_MUSIC
,
STREAM_ALARM
, and
STREAM_NOTIFICATION
.
|
---|---|
sampleRateInHz | the initial source sample rate expressed in Hz. |
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 internal buffer where audio data is
read from for playback.
If track's creation mode is
MODE_STREAM
, you can write data into
this buffer in chunks less than or equal to this size, and it is typical to use
chunks of 1/2 of the total size to permit double-buffering.
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.
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
|
IllegalArgumentException |
---|
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.
streamType |
the type of the audio stream. See
STREAM_VOICE_CALL
,
STREAM_SYSTEM
,
STREAM_RING
,
STREAM_MUSIC
,
STREAM_ALARM
, and
STREAM_NOTIFICATION
.
|
---|---|
sampleRateInHz | the initial source sample rate expressed in Hz. |
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 |
IllegalArgumentException |
---|
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.
effectId | system wide unique id of the effect to attach |
---|
SUCCESS
,
ERROR_INVALID_OPERATION
,
ERROR_BAD_VALUE
Flushes the audio data currently queued for playback. Any data that has
not been played back will be discarded. No-op if not stopped or paused,
or if the track's creation mode is not
MODE_STREAM
.
Returns the configured audio data format. See
ENCODING_PCM_16BIT
and
ENCODING_PCM_8BIT
.
Returns the audio session ID.
Returns the configured channel configuration.
See
CHANNEL_OUT_MONO
and
CHANNEL_OUT_STEREO
.
Returns the maximum valid volume value. Volume values set above this one will be clamped at this value.
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.
sampleRateInHz | the source sample rate expressed in Hz. |
---|---|
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
|
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.
Returns the minimum valid volume value. Volume values set under this one will be clamped at this value.
Returns the output sample rate in Hz for the specified stream type.
Returns marker position expressed in frames.
getPlaybackHeadPosition()
,
or zero if marker is disabled.
Returns the playback state of the AudioTrack instance.
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(), reload(), and stop().
Returns the notification update period expressed in frames. Zero means that no position update notifications are being delivered.
Returns the configured audio data sample rate in Hz
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 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
.
Poll for a timestamp on demand. Use if you need to get the most recent timestamp outside of the event callback handler. Calling this method too often may be inefficient; 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.
timestamp | a reference to a non-null AudioTimestamp instance allocated and owned by caller. |
---|
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.
IllegalStateException |
---|
Starts playing an AudioTrack.
If track's creation mode is
MODE_STATIC
, you must have called write() prior.
IllegalStateException |
---|
Notifies the native resource to reuse the audio data already loaded in the native
layer, that is to rewind to start of buffer.
The track's creation mode must be
MODE_STATIC
.
SUCCESS
,
ERROR_BAD_VALUE
,
ERROR_INVALID_OPERATION
Sets the send level of the audio track to the attached auxiliary effect
attachAuxEffect(int)
. The level value range is 0.0f to 1.0f.
Values are clamped to the (0.0f, 1.0f) interval if outside this range.
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 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)
level | send level scalar |
---|
SUCCESS
,
ERROR_INVALID_OPERATION
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.
startInFrames | 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 | 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. |
loopCount | the number of times the loop is looped. A value of -1 means infinite looping, and 0 disables looping. |
SUCCESS
,
ERROR_BAD_VALUE
,
ERROR_INVALID_OPERATION
Sets the position of the notification marker. At most one marker can be active.
markerInFrames |
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.
|
---|
SUCCESS
,
ERROR_BAD_VALUE
,
ERROR_INVALID_OPERATION
Sets the playback head position.
The track must be stopped or paused for the position to be changed,
and must use the
MODE_STATIC
mode.
positionInFrames | playback head position expressed in frames Zero corresponds to start of buffer. The position must not be greater than the buffer size in frames, or negative. |
---|
SUCCESS
,
ERROR_BAD_VALUE
,
ERROR_INVALID_OPERATION
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.
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.
handler | the Handler that will receive the event notification messages. |
---|
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)
.
sampleRateInHz | the sample rate expressed in Hz |
---|
SUCCESS
,
ERROR_BAD_VALUE
,
ERROR_INVALID_OPERATION
Sets the period for the periodic notification event.
periodInFrames | update period expressed in frames |
---|
SUCCESS
,
ERROR_INVALID_OPERATION
Sets the specified left/right output volume values on the AudioTrack. Values are clamped
to the (
getMinVolume()
,
getMaxVolume()
) interval if outside this range.
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 |
SUCCESS
,
ERROR_INVALID_OPERATION
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.
IllegalStateException |
---|
Writes the audio data to the audio sink for playback (streaming mode),
or copies audio data for later playback (static buffer mode).
In streaming mode, will block until all data has been written to the audio sink.
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. This function is thread safe with respect to
stop()
calls,
in which case all of the specified data might not be written to the audio sink.
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 shorts to read in audioData after the offset. |
ERROR_INVALID_OPERATION
if the object wasn't properly initialized, or
ERROR_BAD_VALUE
if
the parameters don't resolve to valid data and indexes.
Writes the audio data to the audio sink for playback (streaming mode),
or copies audio data for later playback (static buffer mode).
In streaming mode, will block until all data has been written to the audio sink.
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. This function is thread safe with respect to
stop()
calls,
in which case all of the specified data might not be written to the audio sink.
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. |
ERROR_INVALID_OPERATION
if the object wasn't properly initialized, or
ERROR_BAD_VALUE
if
the parameters don't resolve to valid data and indexes.
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.
This method was deprecated
in API level 19.
Only accessible by subclasses, which are not recommended for AudioTrack.
See
getProperty(String)
for key
PROPERTY_OUTPUT_FRAMES_PER_BUFFER
.
Returns the "native frame count", derived from the bufferSizeInBytes specified at
creation time and converted to frame units.
If track's creation mode is
MODE_STATIC
,
it is equal to the specified bufferSizeInBytes converted to frame units.
If track's creation mode is
MODE_STREAM
,
it is typically greater than or equal to the specified bufferSizeInBytes converted to frame
units; it may be rounded up to a larger value if needed by the target device implementation.
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.
state | the state of the AudioTrack instance |
---|