public class AudioTrack extends Object implements Closeable
An audio track allocates a native buffer when it is opened. The audio track should be closed with the
close()
method in order to free the native allocation.
While the audio track is open, the native implementation reads audio data continuously from the buffer and plays it
on the output device. The writeBuffer(byte[], int, int)
method can be used to write a chunk of audio data in
the buffer. If audio data is not written fast enough by the application, the output device may play undesired
silences. The waitForBufferFlushed()
method can be used to wait until all the audio data written in the
buffer has been played back.
The volume of the playback can be configured by calling setVolume(float)
.
Constructor and Description |
---|
AudioTrack(AudioFormat format,
int bufferSize)
Creates and opens an audio track.
|
Modifier and Type | Method and Description |
---|---|
void |
close()
Closes this audio track.
|
int |
getBufferSize()
Returns the buffer size of this audio track.
|
AudioFormat |
getFormat()
Returns the format of this audio track.
|
boolean |
isClosed()
Returns whether this audio track is closed.
|
void |
setVolume(float gain)
Sets the volume of this audio track.
|
boolean |
waitForBufferFlushed()
Waits for the buffer of this audio track to be flushed.
|
int |
writeBuffer(byte[] array,
int offset,
int size)
Writes audio data in the buffer of this audio track.
|
public AudioTrack(AudioFormat format, int bufferSize)
format
- the format.bufferSize
- the buffer size (in bytes).IllegalArgumentException
- if the given buffer size is less than or equal to zero.AudioException
- if the audio track could not be opened.public void close()
This method releases the native resources allocated when opening this audio track. This method does nothing if this audio track is already closed.
close
in interface Closeable
close
in interface AutoCloseable
public int getBufferSize()
public AudioFormat getFormat()
public boolean isClosed()
public void setVolume(float gain)
gain
- the gain (between 0.0f
and 1.0f
).public boolean waitForBufferFlushed()
This method blocks until the buffer is empty (until all the audio data has been played back), until this audio track is closed or until the thread is interrupted.
true
if the buffer is empty, false
if this audio track is closed or the thread
is interrupted.public int writeBuffer(byte[] array, int offset, int size)
This method blocks until the requested size has been written, until this audio track is closed or until the thread is interrupted.
The number of bytes written may be different from the given size if this audio track is closed or until the thread is interrupted.
array
- the array containing the data to write.offset
- the offset in the array of the first byte to write.size
- the maximum number of bytes to write.IndexOutOfBoundsException
- if the given offset or the given size is invalid.