@UnstableApi
public interface AudioSink

Known direct subclasses
DefaultAudioSink

Plays audio data.

ForwardingAudioSink

An overridable AudioSink implementation forwarding all methods to another sink.

Known indirect subclasses
CapturingAudioSink

A ForwardingAudioSink that captures configuration, discontinuity and buffer events.

OggFileAudioBufferSink

A sink for audio buffers that writes output audio as .ogg files with a given path prefix.


A sink that consumes audio data.

Before starting playback, specify the input audio format by calling configure.

Call handleBuffer to write data, and handleDiscontinuity when the data being fed is discontinuous. Call play to start playing the written data.

Call configure whenever the input format changes. The sink will be reinitialized on the next call to handleBuffer.

Call flush to prepare the sink to receive audio data from a new playback position.

Call playToEndOfStream repeatedly to play out all data when no more input buffers will be provided via handleBuffer until the next flush. Call reset when the instance is no longer required.

The implementation may be backed by a platform AudioTrack. In this case, setAudioSessionId, setAudioAttributes, enableTunnelingV21 and disableTunneling may be called before writing data to the sink. These methods may also be called after writing data to the sink, in which case it will be reinitialized as required. For implementations that are not based on platform s, calling methods relating to audio sessions, audio attributes, and tunneling may have no effect.

Summary

Nested types

public final class AudioSink.AudioTrackConfig

Configuration parameters used for an AudioTrack.

public final class AudioSink.ConfigurationException extends Exception

Thrown when a failure occurs configuring the sink.

public final class AudioSink.InitializationException extends Exception

Thrown when a failure occurs initializing the sink.

public interface AudioSink.Listener

Listener for audio sink events.

@Documented
@Retention(value = RetentionPolicy.SOURCE)
@Target(value = TYPE_USE)
@IntDef(value = )
public annotation AudioSink.OffloadMode

Audio offload mode configuration.

@Documented
@Retention(value = RetentionPolicy.SOURCE)
@Target(value = TYPE_USE)
@IntDef(value = )
public annotation AudioSink.SinkFormatSupport

The level of support the sink provides for a format.

Thrown when the sink encounters an unexpected timestamp discontinuity.

public final class AudioSink.WriteException extends Exception

Thrown when a failure occurs writing to the sink.

Constants

default static final long
CURRENT_POSITION_NOT_SET = -9223372036854775808

Returned by getCurrentPositionUs when the position is not set.

default static final int

The audio sink will never play in offload mode.

default static final int

The audio sink will prefer offload playback even if this might result in silence gaps between tracks.

default static final int

The audio sink will prefer offload playback except in the case where both the track is gapless and the device does support gapless offload playback.

default static final int

The sink supports the format directly, without the need for internal transcoding.

default static final int

The sink supports the format, but needs to transcode it internally to do so.

default static final int

The sink does not support the format.

Public methods

abstract void
configure(
    Format inputFormat,
    int specifiedBufferSize,
    @Nullable int[] outputChannels
)

Configures (or reconfigures) the sink.

abstract void

Disables tunneling.

abstract void

Enables tunneling, if possible.

abstract void

Flushes the sink, after which it is ready to receive buffers from a new playback position.

abstract @Nullable AudioAttributes

Returns the audio attributes used for audio playback, or null if the sink does not use audio attributes.

abstract 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.

default AudioOffloadSupport

Returns the level of offload support that the sink can provide for a given Format.

abstract int

Returns the level of support that the sink provides for a given Format.

abstract PlaybackParameters

Returns the active PlaybackParameters.

abstract boolean

Returns whether silences are skipped in the audio stream.

abstract boolean
handleBuffer(
    ByteBuffer buffer,
    long presentationTimeUs,
    int encodedAccessUnitCount
)

Attempts to process data from a ByteBuffer, starting from its current position and ending at its limit (exclusive).

abstract void

Signals to the sink that the next buffer may be discontinuous with the previous buffer.

abstract boolean

Returns whether the sink has data pending that has not been consumed yet.

abstract boolean

Returns whether playToEndOfStream has been called and all buffers have been processed.

abstract void

Pauses playback.

abstract void

Starts or resumes consuming audio if initialized.

abstract void

Processes any remaining data.

default void

Releases the audio sink.

abstract void

Resets the sink, releasing any resources that it currently holds.

abstract void

Sets attributes for audio playback.

abstract void
setAudioSessionId(int audioSessionId)

Sets the audio session id.

abstract void

Sets the auxiliary effect.

default void
setClock(Clock clock)

Sets the Clock to use for timing in this audio sink.

abstract void

Sets the listener for sink events, which should be the audio renderer.

default void
@RequiresApi(value = 29)
setOffloadDelayPadding(int delayInFrames, int paddingInFrames)

Sets offload delay padding on the AudioTrack, if possible.

default void
@RequiresApi(value = 29)
setOffloadMode(@AudioSink.OffloadMode int offloadMode)

Sets audio offload mode, if possible.

default void
setOutputStreamOffsetUs(long outputStreamOffsetUs)

Sets the offset that is added to the media timestamp before it is passed as presentationTimeUs in handleBuffer.

abstract void

Attempts to set the playback parameters.

default void

Sets the PlayerId of the player using this audio sink.

default void
@RequiresApi(value = 23)
setPreferredDevice(@Nullable AudioDeviceInfo audioDeviceInfo)

Sets the preferred audio device.

abstract void
setSkipSilenceEnabled(boolean skipSilenceEnabled)

Sets whether silences should be skipped in the audio stream.

abstract void
setVolume(float volume)

Sets the playback volume.

abstract boolean

Returns whether the sink supports a given Format.

Constants

CURRENT_POSITION_NOT_SET

default static final long CURRENT_POSITION_NOT_SET = -9223372036854775808

Returned by getCurrentPositionUs when the position is not set.

OFFLOAD_MODE_DISABLED

default static final int OFFLOAD_MODE_DISABLED = 0

The audio sink will never play in offload mode.

OFFLOAD_MODE_ENABLED_GAPLESS_NOT_REQUIRED

default static final int OFFLOAD_MODE_ENABLED_GAPLESS_NOT_REQUIRED = 2

The audio sink will prefer offload playback even if this might result in silence gaps between tracks.

Use this option to prioritize battery saving at the cost of a possible non seamless transitions between tracks of the same album.

OFFLOAD_MODE_ENABLED_GAPLESS_REQUIRED

default static final int OFFLOAD_MODE_ENABLED_GAPLESS_REQUIRED = 1

The audio sink will prefer offload playback except in the case where both the track is gapless and the device does support gapless offload playback.

Use this option to prioritize uninterrupted playback of consecutive audio tracks over power savings.

SINK_FORMAT_SUPPORTED_DIRECTLY

default static final int SINK_FORMAT_SUPPORTED_DIRECTLY = 2

The sink supports the format directly, without the need for internal transcoding.

SINK_FORMAT_SUPPORTED_WITH_TRANSCODING

default static final int SINK_FORMAT_SUPPORTED_WITH_TRANSCODING = 1

The sink supports the format, but needs to transcode it internally to do so. Internal transcoding may result in lower quality and higher CPU load in some cases.

SINK_FORMAT_UNSUPPORTED

default static final int SINK_FORMAT_UNSUPPORTED = 0

The sink does not support the format.

Public methods

configure

abstract void configure(
    Format inputFormat,
    int specifiedBufferSize,
    @Nullable int[] outputChannels
)

Configures (or reconfigures) the sink.

Parameters
Format inputFormat

The format of audio data provided in the input buffers.

int specifiedBufferSize

A specific size for the playback buffer in bytes, or 0 to infer a suitable buffer size.

@Nullable int[] outputChannels

A mapping from input to output channels that is applied to this sink'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.

Throws
androidx.media3.exoplayer.audio.AudioSink.ConfigurationException

If an error occurs configuring the sink.

disableTunneling

abstract void disableTunneling()

Disables tunneling. If tunneling was previously enabled then the sink is reset and any audio session id is cleared.

enableTunnelingV21

abstract void enableTunnelingV21()

Enables tunneling, if possible. The sink is reset if tunneling was previously disabled. Enabling tunneling is only possible if the sink is based on a platform AudioTrack, and requires platform API version 21 onwards.

Throws
java.lang.IllegalStateException

Thrown if enabling tunneling on platform API version <21.

flush

abstract void flush()

Flushes the sink, after which it is ready to receive buffers from a new playback position.

The audio session may remain active until reset is called.

getAudioAttributes

abstract @Nullable AudioAttributes getAudioAttributes()

Returns the audio attributes used for audio playback, or null if the sink does not use audio attributes.

getCurrentPositionUs

abstract 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.

Parameters
boolean sourceEnded

Specify true if no more input buffers will be provided.

Returns
long

The playback position relative to the start of playback, in microseconds.

getFormatOffloadSupport

default AudioOffloadSupport getFormatOffloadSupport(Format format)

Returns the level of offload support that the sink can provide for a given Format.

Parameters
Format format

The format.

Returns
AudioOffloadSupport

The level of support provided.

getFormatSupport

@AudioSink.SinkFormatSupport
abstract int getFormatSupport(Format format)

Returns the level of support that the sink provides for a given Format.

Parameters
Format format

The format.

Returns
int

The level of support provided.

getPlaybackParameters

abstract PlaybackParameters getPlaybackParameters()

Returns the active PlaybackParameters.

getSkipSilenceEnabled

abstract boolean getSkipSilenceEnabled()

Returns whether silences are skipped in the audio stream.

handleBuffer

abstract boolean handleBuffer(
    ByteBuffer buffer,
    long presentationTimeUs,
    int encodedAccessUnitCount
)

Attempts to process data from a 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. 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 intervening call to flush (or to configure that causes the sink to be flushed).

Parameters
ByteBuffer buffer

The buffer containing audio data.

long presentationTimeUs

The presentation timestamp of the buffer in microseconds.

int encodedAccessUnitCount

The number of encoded access units in the buffer, or 1 if the buffer contains PCM audio. This allows batching multiple encoded access units in one buffer.

Returns
boolean

Whether the buffer was handled fully.

Throws
androidx.media3.exoplayer.audio.AudioSink.InitializationException

If an error occurs initializing the sink.

androidx.media3.exoplayer.audio.AudioSink.WriteException

If an error occurs writing the audio data.

handleDiscontinuity

abstract void handleDiscontinuity()

Signals to the sink that the next buffer may be discontinuous with the previous buffer.

hasPendingData

abstract boolean hasPendingData()

Returns whether the sink has data pending that has not been consumed yet.

isEnded

abstract boolean isEnded()

Returns whether playToEndOfStream has been called and all buffers have been processed.

pause

abstract void pause()

Pauses playback.

play

abstract void play()

Starts or resumes consuming audio if initialized.

playToEndOfStream

abstract void playToEndOfStream()

Processes any remaining data. isEnded will return true when no data remains.

Throws
androidx.media3.exoplayer.audio.AudioSink.WriteException

If an error occurs draining data to the sink.

release

default void release()

Releases the audio sink.

reset

abstract void reset()

Resets the sink, releasing any resources that it currently holds.

setAudioAttributes

abstract void setAudioAttributes(AudioAttributes audioAttributes)

Sets attributes for audio playback. If the attributes have changed and if the sink is not configured for use with tunneling, then it is reset and the audio session id is cleared.

If the sink is configured for use with tunneling then the audio attributes are ignored. The sink is not reset and the audio session id is not cleared. The passed attributes will be used if the sink is later re-configured into non-tunneled mode.

Parameters
AudioAttributes audioAttributes

The attributes for audio playback.

setAudioSessionId

abstract void setAudioSessionId(int audioSessionId)

Sets the audio session id.

setAuxEffectInfo

abstract void setAuxEffectInfo(AuxEffectInfo auxEffectInfo)

Sets the auxiliary effect.

setClock

default void setClock(Clock clock)

Sets the Clock to use for timing in this audio sink.

Parameters
Clock clock

The Clock.

setListener

abstract void setListener(AudioSink.Listener listener)

Sets the listener for sink events, which should be the audio renderer.

Parameters
AudioSink.Listener listener

The listener for sink events, which should be the audio renderer.

setOffloadDelayPadding

@RequiresApi(value = 29)
default void setOffloadDelayPadding(int delayInFrames, int paddingInFrames)

Sets offload delay padding on the AudioTrack, if possible. Setting the offload delay padding is only possible if the sink is based on a platform AudioTrack in offload mode. Also requires platform API version 29 onwards.

setOffloadMode

@RequiresApi(value = 29)
default void setOffloadMode(@AudioSink.OffloadMode int offloadMode)

Sets audio offload mode, if possible. Enabling offload is only possible if the sink is based on a platform AudioTrack, and requires platform API version 29 onwards.

setOutputStreamOffsetUs

default void setOutputStreamOffsetUs(long outputStreamOffsetUs)

Sets the offset that is added to the media timestamp before it is passed as presentationTimeUs in handleBuffer.

Parameters
long outputStreamOffsetUs

The output stream offset in microseconds.

setPlaybackParameters

abstract void setPlaybackParameters(PlaybackParameters playbackParameters)

Attempts to set the playback parameters. The audio sink may override these parameters if they are not supported.

Parameters
PlaybackParameters playbackParameters

The new playback parameters to attempt to set.

setPlayerId

default void setPlayerId(@Nullable PlayerId playerId)

Sets the PlayerId of the player using this audio sink.

Parameters
@Nullable PlayerId playerId

The PlayerId, or null to clear a previously set id.

setPreferredDevice

@RequiresApi(value = 23)
default void setPreferredDevice(@Nullable AudioDeviceInfo audioDeviceInfo)

Sets the preferred audio device.

Parameters
@Nullable AudioDeviceInfo audioDeviceInfo

The preferred audio device, or null to restore the default.

setSkipSilenceEnabled

abstract void setSkipSilenceEnabled(boolean skipSilenceEnabled)

Sets whether silences should be skipped in the audio stream.

setVolume

abstract void setVolume(float volume)

Sets the playback volume.

Parameters
float volume

Linear output gain to apply to all channels. Should be in the range [0.0, 1.0].

supportsFormat

abstract boolean supportsFormat(Format format)

Returns whether the sink supports a given Format.

Parameters
Format format

The format.

Returns
boolean

Whether the sink supports the format.