IT. Expert System.

Android Reference

AudioTrack


android.media

Class AudioTrack



  • public class AudioTrack
    extends Object
    The AudioTrack class manages and plays a single audio resource for Java applications. It allows streaming PCM audio buffers to the audio hardware 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:

    • too big to fit in memory because of the duration of the sound to play,
    • too big to fit in memory because of the characteristics of the audio data (high sampling rate, bits per sample ...)
    • received or generated while previously queued audio is playing.
    The static mode should be chosen when dealing with short sounds that fit in memory and that need to be played with the smallest latency possible. The static mode will therefore be preferred for UI and game sounds that are played often, and with the smallest overhead possible.

    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 hardware in chunks of sizes less than or equal to the total buffer size.

    • Nested Class Summary

      Nested Classes
      Modifier and Type Class and Description
      static interface 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.
    • Field Summary

      Fields
      Modifier and Type Field and Description
      static int ERROR
      Denotes a generic operation failure.
      static int ERROR_BAD_VALUE
      Denotes a failure due to the use of an invalid value.
      static int ERROR_INVALID_OPERATION
      Denotes a failure due to the improper use of a method.
      static int MODE_STATIC
      Creation mode where audio data is transferred from Java to the native layer only once before the audio starts playing.
      static int MODE_STREAM
      Creation mode where audio data is streamed from Java to the native layer as the audio is playing.
      static int PLAYSTATE_PAUSED
      indicates AudioTrack state is paused
      static int PLAYSTATE_PLAYING
      indicates AudioTrack state is playing
      static int PLAYSTATE_STOPPED
      indicates AudioTrack state is stopped
      static int STATE_INITIALIZED
      State of an AudioTrack that is ready to be used.
      static int STATE_NO_STATIC_DATA
      State of a successfully initialized AudioTrack that uses static data, but that hasn't received that data yet.
      static int STATE_UNINITIALIZED
      State of an AudioTrack that was not successfully initialized upon creation.
      static int SUCCESS
      Denotes a successful operation.
    • Constructor Summary

      Constructors
      Constructor and Description
      AudioTrack(int streamType, int sampleRateInHz, int channelConfig, int audioFormat, int bufferSizeInBytes, int mode)
      Class constructor.
      AudioTrack(int streamType, int sampleRateInHz, int channelConfig, int audioFormat, int bufferSizeInBytes, int mode, int sessionId)
      Class constructor with audio session.
    • Field Detail

      • PLAYSTATE_STOPPED

        public static final int PLAYSTATE_STOPPED
        indicates AudioTrack state is stopped
        See Also:
        Constant Field Values
      • PLAYSTATE_PAUSED

        public static final int PLAYSTATE_PAUSED
        indicates AudioTrack state is paused
        See Also:
        Constant Field Values
      • PLAYSTATE_PLAYING

        public static final int PLAYSTATE_PLAYING
        indicates AudioTrack state is playing
        See Also:
        Constant Field Values
      • MODE_STATIC

        public static final int MODE_STATIC
        Creation mode where audio data is transferred from Java to the native layer only once before the audio starts playing.
        See Also:
        Constant Field Values
      • MODE_STREAM

        public static final int MODE_STREAM
        Creation mode where audio data is streamed from Java to the native layer as the audio is playing.
        See Also:
        Constant Field Values
      • STATE_UNINITIALIZED

        public static final int STATE_UNINITIALIZED
        State of an AudioTrack that was not successfully initialized upon creation.
        See Also:
        Constant Field Values
      • STATE_INITIALIZED

        public static final int STATE_INITIALIZED
        State of an AudioTrack that is ready to be used.
        See Also:
        Constant Field Values
      • STATE_NO_STATIC_DATA

        public static final int STATE_NO_STATIC_DATA
        State of a successfully initialized AudioTrack that uses static data, but that hasn't received that data yet.
        See Also:
        Constant Field Values
      • ERROR

        public static final int ERROR
        Denotes a generic operation failure.
        See Also:
        Constant Field Values
      • ERROR_BAD_VALUE

        public static final int ERROR_BAD_VALUE
        Denotes a failure due to the use of an invalid value.
        See Also:
        Constant Field Values
      • ERROR_INVALID_OPERATION

        public static final int ERROR_INVALID_OPERATION
        Denotes a failure due to the improper use of a method.
        See Also:
        Constant Field Values
    • Method Detail

      • release

        public void release()
        Releases the native AudioTrack resources.
      • finalize

        protected void finalize()
        Description copied from class: Object
        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.

        Overrides:
        finalize in class Object
      • getMinVolume

        public static float getMinVolume()
        Returns the minimum valid volume value. Volume values set under this one will be clamped at this value.
        Returns:
        the minimum volume expressed as a linear attenuation.
      • getMaxVolume

        public static float getMaxVolume()
        Returns the maximum valid volume value. Volume values set above this one will be clamped at this value.
        Returns:
        the maximum volume expressed as a linear attenuation.
      • getSampleRate

        public int getSampleRate()
        Returns the configured audio data sample rate in Hz
      • getPlaybackRate

        public int getPlaybackRate()
        Returns the current playback rate in Hz.
      • getChannelCount

        public int getChannelCount()
        Returns the configured number of channels.
      • getState

        public int getState()
        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 hardware resources have been acquired.
        See Also:
        STATE_INITIALIZED, STATE_NO_STATIC_DATA, STATE_UNINITIALIZED
      • getNativeFrameCount

        protected int getNativeFrameCount()
        Returns the native frame count used by the hardware.
      • getNotificationMarkerPosition

        public int getNotificationMarkerPosition()
        Returns marker position expressed in frames.
      • getPositionNotificationPeriod

        public int getPositionNotificationPeriod()
        Returns the notification update period expressed in frames.
      • getPlaybackHeadPosition

        public int getPlaybackHeadPosition()
        Returns the playback head position expressed in frames
      • getNativeOutputSampleRate

        public static int getNativeOutputSampleRate(int streamType)
        Returns the hardware output sample rate
      • getMinBufferSize

        public static int getMinBufferSize(int sampleRateInHz,
                           int channelConfig,
                           int audioFormat)
        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.
        Parameters:
        sampleRateInHz - the sample rate expressed in Hertz.
        channelConfig - describes the configuration of the audio channels. See AudioFormat.CHANNEL_OUT_MONO and AudioFormat.CHANNEL_OUT_STEREO
        audioFormat - the format in which the audio data is represented. See AudioFormat.ENCODING_PCM_16BIT and AudioFormat.ENCODING_PCM_8BIT
        Returns:
        ERROR_BAD_VALUE if an invalid parameter was passed, or ERROR if the implementation was unable to query the hardware for its output properties, or the minimum buffer size expressed in bytes.
      • getAudioSessionId

        public int getAudioSessionId()
        Returns the audio session ID.
        Returns:
        the ID of the audio session this AudioTrack belongs to.
      • setPlaybackPositionUpdateListener

        public void setPlaybackPositionUpdateListener(AudioTrack.OnPlaybackPositionUpdateListener listener)
        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.
        Parameters:
        listener -
      • setPlaybackPositionUpdateListener

        public void setPlaybackPositionUpdateListener(AudioTrack.OnPlaybackPositionUpdateListener listener,
                                             Handler handler)
        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.
        Parameters:
        listener -
        handler - the Handler that will receive the event notification messages.
      • setStereoVolume

        public int setStereoVolume(float leftVolume,
                          float rightVolume)
        Sets the specified left/right output volume values on the AudioTrack. Values are clamped to the (getMinVolume(), getMaxVolume()) interval if outside this range.
        Parameters:
        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
        Returns:
        error code or success, see SUCCESS, ERROR_INVALID_OPERATION
      • setPlaybackRate

        public int setPlaybackRate(int sampleRateInHz)
        Sets the playback sample rate for this track. This sets the sampling rate at which the audio data will be consumed and played back, not the original sampling rate of the content. 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 negative pitch shift. The valid sample rate range is from 1Hz to twice the value returned by getNativeOutputSampleRate(int).
        Parameters:
        sampleRateInHz - the sample rate expressed in Hz
        Returns:
        error code or success, see SUCCESS, ERROR_BAD_VALUE, ERROR_INVALID_OPERATION
      • setNotificationMarkerPosition

        public int setNotificationMarkerPosition(int markerInFrames)
        Sets the position of the notification marker.
        Parameters:
        markerInFrames - marker in frames
        Returns:
        error code or success, see SUCCESS, ERROR_BAD_VALUE, ERROR_INVALID_OPERATION
      • setPositionNotificationPeriod

        public int setPositionNotificationPeriod(int periodInFrames)
        Sets the period for the periodic notification event.
        Parameters:
        periodInFrames - update period expressed in frames
        Returns:
        error code or success, see SUCCESS, ERROR_INVALID_OPERATION
      • setPlaybackHeadPosition

        public int setPlaybackHeadPosition(int positionInFrames)
        Sets the playback head position. The track must be stopped for the position to be changed.
        Parameters:
        positionInFrames - playback head position expressed in frames
        Returns:
        error code or success, see SUCCESS, ERROR_BAD_VALUE, ERROR_INVALID_OPERATION
      • setLoopPoints

        public int setLoopPoints(int startInFrames,
                        int endInFrames,
                        int loopCount)
        Sets the loop points and the loop count. The loop can be infinite.
        Parameters:
        startInFrames - loop start marker expressed in frames
        endInFrames - loop end marker expressed in frames
        loopCount - the number of times the loop is looped. A value of -1 means infinite looping.
        Returns:
        error code or success, see SUCCESS, ERROR_BAD_VALUE, ERROR_INVALID_OPERATION
      • setState

        protected void setState(int state)
        Sets the initialization state of the instance. To be used in an AudioTrack subclass constructor to set a subclass-specific post-initialization state.
        Parameters:
        state - the state of the AudioTrack instance
      • stop

        public void stop()
                  throws IllegalStateException
        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.
        Throws:
        IllegalStateException
      • flush

        public void flush()
        Flushes the audio data currently queued for playback. Any data that has not been played back will be discarded.
      • write

        public int write(byte[] audioData,
                int offsetInBytes,
                int sizeInBytes)
        Writes the audio data to the audio hardware for playback. Will block until all data has been written to the audio mixer. 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 mixer.
        Parameters:
        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.
        Returns:
        the number of bytes that were written or 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.
      • write

        public int write(short[] audioData,
                int offsetInShorts,
                int sizeInShorts)
        Writes the audio data to the audio hardware for playback. Will block until all data has been written to the audio mixer. 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 mixer.
        Parameters:
        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 bytes to read in audioData after the offset.
        Returns:
        the number of shorts that were written or 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.
      • reloadStaticData

        public int reloadStaticData()
        Notifies the native resource to reuse the audio data already loaded in the native layer. This call is only valid with AudioTrack instances that don't use the streaming model.
        Returns:
        error code or success, see SUCCESS, ERROR_BAD_VALUE, ERROR_INVALID_OPERATION
      • attachAuxEffect

        public int attachAuxEffect(int effectId)
        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(). setAuxEffectSendLevel(float).

        After creating an auxiliary effect (e.g. EnvironmentalReverb), retrieve its ID with AudioEffect.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.

        Parameters:
        effectId - system wide unique id of the effect to attach
        Returns:
        error code or success, see SUCCESS, ERROR_INVALID_OPERATION, ERROR_BAD_VALUE
      • setAuxEffectSendLevel

        public int setAuxEffectSendLevel(float level)
        Sets the send level of the audio track to the attached auxiliary effect attachAuxEffect(int). The level value range is 0 to 1.0.

        By default the send level is 0, 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)

        Parameters:
        level - send level scalar
        Returns:
        error code or success, see SUCCESS, ERROR_INVALID_OPERATION


Content

Android Reference

Java basics

Java Enterprise Edition (EE)

Java Standard Edition (SE)

SQL

HTML

PHP

CSS

Java Script

MYSQL

JQUERY

VBS

REGEX

C

C++

C#

Design patterns

RFC (standard status)

RFC (proposed standard status)

RFC (draft standard status)

RFC (informational status)

RFC (experimental status)

RFC (best current practice status)

RFC (historic status)

RFC (unknown status)

IT dictionary

License.
All information of this service is derived from the free sources and is provided solely in the form of quotations. This service provides information and interfaces solely for the familiarization (not ownership) and under the "as is" condition.
Copyright 2016 © ELTASK.COM. All rights reserved.
Site is optimized for mobile devices.
Downloads: 369 / . Delta: 0.01644 с