Class DefaultAudioSink

  • All Implemented Interfaces:
    AudioSink

    public final class DefaultAudioSink
    extends Object
    implements AudioSink
    Plays audio data. The implementation delegates to an AudioTrack and handles playback position smoothing, non-blocking writes and reconfiguration.

    If tunneling mode 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. This means that, for example, speed adjustment is not possible while using tunneling.

    • Field Detail

      • DEFAULT_PLAYBACK_SPEED

        public static final float DEFAULT_PLAYBACK_SPEED
        The default playback speed.
        See Also:
        Constant Field Values
      • MIN_PLAYBACK_SPEED

        public static final float MIN_PLAYBACK_SPEED
        The minimum allowed playback speed. Lower values will be constrained to fall in range.
        See Also:
        Constant Field Values
      • MAX_PLAYBACK_SPEED

        public static final float MAX_PLAYBACK_SPEED
        The maximum allowed playback speed. Higher values will be constrained to fall in range.
        See Also:
        Constant Field Values
      • MIN_PITCH

        public static final float MIN_PITCH
        The minimum allowed pitch factor. Lower values will be constrained to fall in range.
        See Also:
        Constant Field Values
      • MAX_PITCH

        public static final float MAX_PITCH
        The maximum allowed pitch factor. Higher values will be constrained to fall in range.
        See Also:
        Constant Field Values
      • OFFLOAD_MODE_DISABLED

        public static final int OFFLOAD_MODE_DISABLED
        The audio sink will never play in offload mode.
        See Also:
        Constant Field Values
      • OFFLOAD_MODE_ENABLED_GAPLESS_REQUIRED

        public static final int OFFLOAD_MODE_ENABLED_GAPLESS_REQUIRED
        The audio sink will prefer offload playback except if the track is gapless and the device does not advertise support for gapless playback in offload.

        Use this option to prioritize seamless transitions between tracks of the same album to power savings.

        See Also:
        Constant Field Values
      • OFFLOAD_MODE_ENABLED_GAPLESS_NOT_REQUIRED

        public static final int OFFLOAD_MODE_ENABLED_GAPLESS_NOT_REQUIRED
        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.

        See Also:
        Constant Field Values
      • OFFLOAD_MODE_ENABLED_GAPLESS_DISABLED

        public static final int OFFLOAD_MODE_ENABLED_GAPLESS_DISABLED
        The audio sink will prefer offload playback, disabling gapless offload support.

        Use this option if gapless has undesirable side effects. For example if it introduces hardware issues.

        See Also:
        Constant Field Values
    • Constructor Detail

      • DefaultAudioSink

        public DefaultAudioSink​(@Nullable
                                AudioCapabilities audioCapabilities,
                                AudioProcessor[] audioProcessors)
        Creates a new default audio sink.
        Parameters:
        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.
      • DefaultAudioSink

        public DefaultAudioSink​(@Nullable
                                AudioCapabilities audioCapabilities,
                                AudioProcessor[] audioProcessors,
                                boolean enableFloatOutput)
        Creates a new default audio sink, optionally using float output for high resolution PCM.
        Parameters:
        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.
        enableFloatOutput - Whether to enable 32-bit float output. Where possible, 32-bit float output will be used if the input is 32-bit float, and also if the input is high resolution (24-bit or 32-bit) integer PCM. Audio processing (for example, speed adjustment) will not be available when float output is in use.
      • DefaultAudioSink

        public DefaultAudioSink​(@Nullable
                                AudioCapabilities audioCapabilities,
                                DefaultAudioSink.AudioProcessorChain audioProcessorChain,
                                boolean enableFloatOutput,
                                boolean enableAudioTrackPlaybackParams,
                                @OffloadMode
                                int offloadMode)
        Creates a new default audio sink, optionally using float output for high resolution PCM and with the specified audioProcessorChain.
        Parameters:
        audioCapabilities - The audio capabilities for playback on this device. May be null if the default capabilities (no encoded audio passthrough support) should be assumed.
        audioProcessorChain - An DefaultAudioSink.AudioProcessorChain which is used to apply playback parameters adjustments. The instance passed in must not be reused in other sinks.
        enableFloatOutput - Whether to enable 32-bit float output. Where possible, 32-bit float output will be used if the input is 32-bit float, and also if the input is high resolution (24-bit or 32-bit) integer PCM. Float output is supported from API level 21. Audio processing (for example, speed adjustment) will not be available when float output is in use.
        enableAudioTrackPlaybackParams - Whether to enable setting playback speed using AudioTrack.setPlaybackParams(PlaybackParams), if supported.
        offloadMode - Audio offload configuration. If an audio format can be both played with offload and encoded audio passthrough, it will be played in offload. Audio offload is supported from API level 29. Most Android devices can only support one offload AudioTrack at a time and can invalidate it at any time. Thus an app can never be guaranteed that it will be able to play in offload. Audio processing (for example, speed adjustment) will not be available when offload is in use.
    • Method Detail

      • setListener

        public void setListener​(AudioSink.Listener listener)
        Description copied from interface: AudioSink
        Sets the listener for sink events, which should be the audio renderer.
        Specified by:
        setListener in interface AudioSink
        Parameters:
        listener - The listener for sink events, which should be the audio renderer.
      • supportsFormat

        public boolean supportsFormat​(Format format)
        Description copied from interface: AudioSink
        Returns whether the sink supports a given Format.
        Specified by:
        supportsFormat in interface AudioSink
        Parameters:
        format - The format.
        Returns:
        Whether the sink supports the format.
      • getFormatSupport

        @SinkFormatSupport
        public int getFormatSupport​(Format format)
        Description copied from interface: AudioSink
        Returns the level of support that the sink provides for a given Format.
        Specified by:
        getFormatSupport in interface AudioSink
        Parameters:
        format - The format.
        Returns:
        The level of support provided.
      • getCurrentPositionUs

        public long getCurrentPositionUs​(boolean sourceEnded)
        Description copied from interface: AudioSink
        Returns the playback position in the stream starting at zero, in microseconds, or AudioSink.CURRENT_POSITION_NOT_SET if it is not yet available.
        Specified by:
        getCurrentPositionUs in interface AudioSink
        Parameters:
        sourceEnded - Specify true if no more input buffers will be provided.
        Returns:
        The playback position relative to the start of playback, in microseconds.
      • configure

        public void configure​(Format inputFormat,
                              int specifiedBufferSize,
                              @Nullable
                              int[] outputChannels)
                       throws AudioSink.ConfigurationException
        Description copied from interface: AudioSink
        Configures (or reconfigures) the sink.
        Specified by:
        configure in interface AudioSink
        Parameters:
        inputFormat - The format of audio data provided in the input buffers.
        specifiedBufferSize - A specific size for the playback buffer in bytes, or 0 to infer a suitable buffer size.
        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:
        AudioSink.ConfigurationException - If an error occurs configuring the sink.
      • play

        public void play()
        Description copied from interface: AudioSink
        Starts or resumes consuming audio if initialized.
        Specified by:
        play in interface AudioSink
      • handleDiscontinuity

        public void handleDiscontinuity()
        Description copied from interface: AudioSink
        Signals to the sink that the next buffer may be discontinuous with the previous buffer.
        Specified by:
        handleDiscontinuity in interface AudioSink
      • handleBuffer

        public boolean handleBuffer​(ByteBuffer buffer,
                                    long presentationTimeUs,
                                    int encodedAccessUnitCount)
                             throws AudioSink.InitializationException,
                                    AudioSink.WriteException
        Description copied from interface: AudioSink
        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. AudioSink.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 intervening call to AudioSink.flush() (or to AudioSink.configure(Format, int, int[]) that causes the sink to be flushed).

        Specified by:
        handleBuffer in interface AudioSink
        Parameters:
        buffer - The buffer containing audio data.
        presentationTimeUs - The presentation timestamp of the buffer in microseconds.
        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:
        Whether the buffer was handled fully.
        Throws:
        AudioSink.InitializationException - If an error occurs initializing the sink.
        AudioSink.WriteException - If an error occurs writing the audio data.
      • hasPendingData

        public boolean hasPendingData()
        Description copied from interface: AudioSink
        Returns whether the sink has data pending that has not been consumed yet.
        Specified by:
        hasPendingData in interface AudioSink
      • setPlaybackParameters

        public void setPlaybackParameters​(PlaybackParameters playbackParameters)
        Description copied from interface: AudioSink
        Attempts to set the playback parameters. The audio sink may override these parameters if they are not supported.
        Specified by:
        setPlaybackParameters in interface AudioSink
        Parameters:
        playbackParameters - The new playback parameters to attempt to set.
      • setSkipSilenceEnabled

        public void setSkipSilenceEnabled​(boolean skipSilenceEnabled)
        Description copied from interface: AudioSink
        Sets whether silences should be skipped in the audio stream.
        Specified by:
        setSkipSilenceEnabled in interface AudioSink
      • getSkipSilenceEnabled

        public boolean getSkipSilenceEnabled()
        Description copied from interface: AudioSink
        Returns whether silences are skipped in the audio stream.
        Specified by:
        getSkipSilenceEnabled in interface AudioSink
      • setAudioAttributes

        public void setAudioAttributes​(AudioAttributes audioAttributes)
        Description copied from interface: AudioSink
        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.

        Specified by:
        setAudioAttributes in interface AudioSink
        Parameters:
        audioAttributes - The attributes for audio playback.
      • setAudioSessionId

        public void setAudioSessionId​(int audioSessionId)
        Description copied from interface: AudioSink
        Sets the audio session id.
        Specified by:
        setAudioSessionId in interface AudioSink
      • enableTunnelingV21

        public void enableTunnelingV21()
        Description copied from interface: AudioSink
        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.
        Specified by:
        enableTunnelingV21 in interface AudioSink
      • disableTunneling

        public void disableTunneling()
        Description copied from interface: AudioSink
        Disables tunneling. If tunneling was previously enabled then the sink is reset and any audio session id is cleared.
        Specified by:
        disableTunneling in interface AudioSink
      • setVolume

        public void setVolume​(float volume)
        Description copied from interface: AudioSink
        Sets the playback volume.
        Specified by:
        setVolume in interface AudioSink
        Parameters:
        volume - Linear output gain to apply to all channels. Should be in the range [0.0, 1.0].
      • pause

        public void pause()
        Description copied from interface: AudioSink
        Pauses playback.
        Specified by:
        pause in interface AudioSink
      • flush

        public void flush()
        Description copied from interface: AudioSink
        Flushes the sink, after which it is ready to receive buffers from a new playback position.

        The audio session may remain active until AudioSink.reset() is called.

        Specified by:
        flush in interface AudioSink
      • reset

        public void reset()
        Description copied from interface: AudioSink
        Resets the sink, releasing any resources that it currently holds.
        Specified by:
        reset in interface AudioSink