AudioRecord


public class AudioRecord
extends Object implements AudioRouting, MicrophoneDirection, AudioRecordingMonitor

java.lang.Object
   ↳ android.media.AudioRecord


The AudioRecord class manages the audio resources for Java applications to record audio from the audio input hardware of the platform. This is achieved by "pulling" (reading) the data from the AudioRecord object. The application is responsible for polling the AudioRecord object in time using one of the following three methods: read(byte[], int, int), read(short[], int, int) or read(java.nio.ByteBuffer, int). The choice of which method to use will be based on the audio data storage format that is the most convenient for the user of AudioRecord.

Upon creation, an AudioRecord object initializes its associated audio buffer that it will fill with the new audio data. The size of this buffer, specified during the construction, determines how long an AudioRecord can record before "over-running" data that has not been read yet. Data should be read from the audio hardware in chunks of sizes inferior to the total recording buffer size.

Applications creating an AudioRecord instance need Manifest.permission.RECORD_AUDIO or the Builder will throw UnsupportedOperationException on build(), and the constructor will return an instance in state STATE_UNINITIALIZED.

Summary

Nested classes

class AudioRecord.Builder

Builder class for AudioRecord objects. 

class AudioRecord.MetricsConstants

 

interface AudioRecord.OnRecordPositionUpdateListener

Interface definition for a callback to be invoked when an AudioRecord has reached a notification marker set by AudioRecord#setNotificationMarkerPosition(int) or for periodic updates on the progress of the record head, as set by AudioRecord#setPositionNotificationPeriod(int)

interface AudioRecord.OnRoutingChangedListener

This interface was deprecated in API level 24. users should switch to the general purpose AudioRouting.OnRoutingChangedListener class instead. 

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_DEAD_OBJECT

An error code indicating that the object reporting it is no longer valid and needs to be recreated.

int ERROR_INVALID_OPERATION

Denotes a failure due to the improper use of a method.

int READ_BLOCKING

The read mode indicating the read operation will block until all data requested has been read.

int READ_NON_BLOCKING

The read mode indicating the read operation will return immediately after reading as much audio data as possible without blocking.

int RECORDSTATE_RECORDING

indicates AudioRecord recording state is recording

int RECORDSTATE_STOPPED

indicates AudioRecord recording state is not recording

int STATE_INITIALIZED

indicates AudioRecord state is ready to be used

int STATE_UNINITIALIZED

indicates AudioRecord state is not successfully initialized.

int SUCCESS

Denotes a successful operation.

Inherited constants

Public constructors

AudioRecord(int audioSource, int sampleRateInHz, int channelConfig, int audioFormat, int bufferSizeInBytes)

Class constructor.

Public methods

void addOnRoutingChangedListener(AudioRecord.OnRoutingChangedListener listener, Handler handler)

This method was deprecated in API level 24. users should switch to the general purpose AudioRouting.OnRoutingChangedListener class instead.

void addOnRoutingChangedListener(AudioRouting.OnRoutingChangedListener listener, Handler handler)

Adds an AudioRouting.OnRoutingChangedListener to receive notifications of routing changes on this AudioRecord.

List<MicrophoneInfo> getActiveMicrophones()

Returns a lists of MicrophoneInfo representing the active microphones.

AudioRecordingConfiguration getActiveRecordingConfiguration()

Returns the current active audio recording for this audio recorder.

int getAudioFormat()

Returns the configured audio data encoding.

int getAudioSessionId()

Returns the audio session ID.

int getAudioSource()

Returns the audio recording source.

int getBufferSizeInFrames()

Returns the frame count of the native AudioRecord buffer.

int getChannelConfiguration()

Returns the configured channel position mask.

int getChannelCount()

Returns the configured number of channels.

AudioFormat getFormat()

Returns the configured AudioRecord format.

LogSessionId getLogSessionId()

Returns the LogSessionId.

PersistableBundle getMetrics()

Return Metrics data about the current AudioTrack instance.

static int getMinBufferSize(int sampleRateInHz, int channelConfig, int audioFormat)

Returns the minimum buffer size required for the successful creation of an AudioRecord object, in byte units.

int getNotificationMarkerPosition()

Returns the notification marker position expressed in frames.

int getPositionNotificationPeriod()

Returns the notification update period expressed in frames.

AudioDeviceInfo getPreferredDevice()

Returns the selected input specified by setPreferredDevice(AudioDeviceInfo).

int getRecordingState()

Returns the recording state of the AudioRecord instance.

AudioDeviceInfo getRoutedDevice()

Returns an AudioDeviceInfo identifying the current routing of this AudioRecord.

int getSampleRate()

Returns the configured audio sink sample rate in Hz.

int getState()

Returns the state of the AudioRecord instance.

int getTimestamp(AudioTimestamp outTimestamp, int timebase)

Poll for an AudioTimestamp on demand.

boolean isPrivacySensitive()

Returns whether this AudioRecord is marked as privacy sensitive or not.

int read(short[] audioData, int offsetInShorts, int sizeInShorts, int readMode)

Reads audio data from the audio hardware for recording into a short array.

int read(ByteBuffer audioBuffer, int sizeInBytes, int readMode)

Reads audio data from the audio hardware for recording into a direct buffer.

int read(short[] audioData, int offsetInShorts, int sizeInShorts)

Reads audio data from the audio hardware for recording into a short array.

int read(float[] audioData, int offsetInFloats, int sizeInFloats, int readMode)

Reads audio data from the audio hardware for recording into a float array.

int read(byte[] audioData, int offsetInBytes, int sizeInBytes, int readMode)

Reads audio data from the audio hardware for recording into a byte array.

int read(ByteBuffer audioBuffer, int sizeInBytes)

Reads audio data from the audio hardware for recording into a direct buffer.

int read(byte[] audioData, int offsetInBytes, int sizeInBytes)

Reads audio data from the audio hardware for recording into a byte array.

void registerAudioRecordingCallback(Executor executor, AudioManager.AudioRecordingCallback cb)

Register a callback to be notified of audio capture changes via a AudioManager.AudioRecordingCallback.

void release()

Releases the native AudioRecord resources.

void removeOnRoutingChangedListener(AudioRecord.OnRoutingChangedListener listener)

This method was deprecated in API level 24. users should switch to the general purpose AudioRouting.OnRoutingChangedListener class instead.

void removeOnRoutingChangedListener(AudioRouting.OnRoutingChangedListener listener)

Removes an AudioRouting.OnRoutingChangedListener which has been previously added to receive rerouting notifications.

void setLogSessionId(LogSessionId logSessionId)

Sets a LogSessionId instance to this AudioRecord for metrics collection.

int setNotificationMarkerPosition(int markerInFrames)

Sets the marker position at which the listener is called, if set with setRecordPositionUpdateListener(android.media.AudioRecord.OnRecordPositionUpdateListener) or setRecordPositionUpdateListener(android.media.AudioRecord.OnRecordPositionUpdateListener, android.os.Handler).

int setPositionNotificationPeriod(int periodInFrames)

Sets the period at which the listener is called, if set with setRecordPositionUpdateListener(android.media.AudioRecord.OnRecordPositionUpdateListener) or setRecordPositionUpdateListener(android.media.AudioRecord.OnRecordPositionUpdateListener, android.os.Handler).

boolean setPreferredDevice(AudioDeviceInfo deviceInfo)

Specifies an audio device (via an AudioDeviceInfo object) to route the input to this AudioRecord.

boolean setPreferredMicrophoneDirection(int direction)

Specifies the logical microphone (for processing).

boolean setPreferredMicrophoneFieldDimension(float zoom)

Specifies the zoom factor (i.e.

void setRecordPositionUpdateListener(AudioRecord.OnRecordPositionUpdateListener listener)

Sets the listener the AudioRecord notifies when a previously set marker is reached or for each periodic record head position update.

void setRecordPositionUpdateListener(AudioRecord.OnRecordPositionUpdateListener listener, Handler handler)

Sets the listener the AudioRecord notifies when a previously set marker is reached or for each periodic record head position update.

void startRecording(MediaSyncEvent syncEvent)

Starts recording from the AudioRecord instance when the specified synchronization event occurs on the specified audio session.

void startRecording()

Starts recording from the AudioRecord instance.

void stop()

Stops recording.

void unregisterAudioRecordingCallback(AudioManager.AudioRecordingCallback cb)

Unregister an audio recording callback previously registered with registerAudioRecordingCallback(java.util.concurrent.Executor, android.media.AudioManager.AudioRecordingCallback).

Protected methods

void finalize()

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

Inherited methods

Constants

ERROR

Added in API level 3
public static final int ERROR

Denotes a generic operation failure.

Constant Value: -1 (0xffffffff)

ERROR_BAD_VALUE

Added in API level 3
public static final int ERROR_BAD_VALUE

Denotes a failure due to the use of an invalid value.

Constant Value: -2 (0xfffffffe)

ERROR_DEAD_OBJECT

Added in API level 24
public static final int ERROR_DEAD_OBJECT

An error code indicating that the object reporting it is no longer valid and needs to be recreated.

Constant Value: -6 (0xfffffffa)

ERROR_INVALID_OPERATION

Added in API level 3
public static final int ERROR_INVALID_OPERATION

Denotes a failure due to the improper use of a method.

Constant Value: -3 (0xfffffffd)

READ_BLOCKING

Added in API level 23
public static final int READ_BLOCKING

The read mode indicating the read operation will block until all data requested has been read.

Constant Value: 0 (0x00000000)

READ_NON_BLOCKING

Added in API level 23
public static final int READ_NON_BLOCKING

The read mode indicating the read operation will return immediately after reading as much audio data as possible without blocking.

Constant Value: 1 (0x00000001)

RECORDSTATE_RECORDING

Added in API level 3
public static final int RECORDSTATE_RECORDING

indicates AudioRecord recording state is recording

Constant Value: 3 (0x00000003)

RECORDSTATE_STOPPED

Added in API level 3
public static final int RECORDSTATE_STOPPED

indicates AudioRecord recording state is not recording

Constant Value: 1 (0x00000001)

STATE_INITIALIZED

Added in API level 3
public static final int STATE_INITIALIZED

indicates AudioRecord state is ready to be used

Constant Value: 1 (0x00000001)

STATE_UNINITIALIZED

Added in API level 3
public static final int STATE_UNINITIALIZED

indicates AudioRecord state is not successfully initialized.

Constant Value: 0 (0x00000000)

SUCCESS

Added in API level 3
public static final int SUCCESS

Denotes a successful operation.

Constant Value: 0 (0x00000000)

Public constructors

AudioRecord

Added in API level 3
public AudioRecord (int audioSource, 
                int sampleRateInHz, 
                int channelConfig, 
                int audioFormat, 
                int bufferSizeInBytes)

Class constructor. Though some invalid parameters will result in an IllegalArgumentException exception, other errors do not. Thus you should call getState() immediately after construction to confirm that the object is usable.
Requires Manifest.permission.RECORD_AUDIO

Parameters
audioSource int: the recording source. See MediaRecorder.AudioSource for the recording source definitions.

sampleRateInHz int: the sample rate expressed in Hertz. 44100Hz is currently the only rate that is guaranteed to work on all devices, but other rates such as 22050, 16000, and 11025 may work on some devices. AudioFormat#SAMPLE_RATE_UNSPECIFIED means to use a route-dependent value which is usually the sample rate of the source. getSampleRate() can be used to retrieve the actual sample rate chosen.

channelConfig int: describes the configuration of the audio channels. See AudioFormat#CHANNEL_IN_MONO and AudioFormat#CHANNEL_IN_STEREO. AudioFormat#CHANNEL_IN_MONO is guaranteed to work on all devices.

audioFormat int: the format in which the audio data is to be returned. See AudioFormat#ENCODING_PCM_8BIT, AudioFormat#ENCODING_PCM_16BIT, and AudioFormat#ENCODING_PCM_FLOAT.

bufferSizeInBytes int: the total size (in bytes) of the buffer where audio data is written to during the recording. New audio data can be read from this buffer in smaller chunks than this size. See getMinBufferSize(int, int, int) to determine the minimum required buffer size for the successful creation of an AudioRecord instance. Using values smaller than getMinBufferSize() will result in an initialization failure.

Throws
java.lang.IllegalArgumentException
IllegalArgumentException

Public methods

addOnRoutingChangedListener

Added in API level 23
Deprecated in API level 24
public void addOnRoutingChangedListener (AudioRecord.OnRoutingChangedListener listener, 
                Handler handler)

This method was deprecated in API level 24.
users should switch to the general purpose AudioRouting.OnRoutingChangedListener class instead.

Adds an OnRoutingChangedListener to receive notifications of routing changes on this AudioRecord.

Parameters
listener AudioRecord.OnRoutingChangedListener: The OnRoutingChangedListener interface to receive notifications of rerouting events.

handler Handler: Specifies the Handler object for the thread on which to execute the callback. If null, the Handler associated with the main Looper will be used.

addOnRoutingChangedListener

Added in API level 24
public void addOnRoutingChangedListener (AudioRouting.OnRoutingChangedListener listener, 
                Handler handler)

Adds an AudioRouting.OnRoutingChangedListener to receive notifications of routing changes on this AudioRecord.

Parameters
listener AudioRouting.OnRoutingChangedListener: The AudioRouting.OnRoutingChangedListener interface to receive notifications of rerouting events.

handler Handler: Specifies the Handler object for the thread on which to execute the callback. If null, the Handler associated with the main Looper will be used.

getActiveMicrophones

Added in API level 28
public List<MicrophoneInfo> getActiveMicrophones ()

Returns a lists of MicrophoneInfo representing the active microphones. By querying channel mapping for each active microphone, developer can know how the microphone is used by each channels or a capture stream. Note that the information about the active microphones may change during a recording. See AudioManager#registerAudioDeviceCallback to be notified of changes in the audio devices, querying the active microphones then will return the latest information.

Returns
List<MicrophoneInfo> a lists of MicrophoneInfo representing the active microphones.

Throws
IOException if an error occurs

getActiveRecordingConfiguration

Added in API level 29
public AudioRecordingConfiguration getActiveRecordingConfiguration ()

Returns the current active audio recording for this audio recorder.

Returns
AudioRecordingConfiguration a valid AudioRecordingConfiguration if this recorder is active or null otherwise.

getAudioFormat

Added in API level 3
public int getAudioFormat ()

Returns the configured audio data encoding. See AudioFormat#ENCODING_PCM_8BIT, AudioFormat#ENCODING_PCM_16BIT, and AudioFormat#ENCODING_PCM_FLOAT.

Returns
int

getAudioSessionId

Added in API level 16
public int getAudioSessionId ()

Returns the audio session ID.

Returns
int the ID of the audio session this AudioRecord belongs to.

getAudioSource

Added in API level 3
public int getAudioSource ()

Returns the audio recording source.

Returns
int

getBufferSizeInFrames

Added in API level 23
public int getBufferSizeInFrames ()

Returns the frame count of the native AudioRecord buffer. This is greater than or equal to the bufferSizeInBytes converted to frame units specified in the AudioRecord constructor or Builder. The native frame count may be enlarged to accommodate the requirements of the source on creation or if the AudioRecord is subsequently rerouted.

Returns
int current size in frames of the AudioRecord buffer.

Throws
java.lang.IllegalStateException

getChannelConfiguration

Added in API level 3
public int getChannelConfiguration ()

Returns the configured channel position mask.

See AudioFormat#CHANNEL_IN_MONO and AudioFormat#CHANNEL_IN_STEREO. This method may return AudioFormat#CHANNEL_INVALID if a channel index mask is used. Consider getFormat() instead, to obtain an AudioFormat, which contains both the channel position mask and the channel index mask.

Returns
int

getChannelCount

Added in API level 3
public int getChannelCount ()

Returns the configured number of channels.

Returns
int

getFormat

Added in API level 23
public AudioFormat getFormat ()

Returns the configured AudioRecord format.

Returns
AudioFormat an AudioFormat containing the AudioRecord parameters at the time of configuration. This value cannot be null.

getLogSessionId

Added in API level 31
public LogSessionId getLogSessionId ()

Returns the LogSessionId.

Returns
LogSessionId This value cannot be null.

getMetrics

Added in API level 28
public PersistableBundle getMetrics ()

Return Metrics data about the current AudioTrack instance.

Returns
PersistableBundle a PersistableBundle containing the set of attributes and values available for the media being handled by this instance of AudioRecord The attributes are descibed in MetricsConstants. Additional vendor-specific fields may also be present in the return value.

getMinBufferSize

Added in API level 3
public static int getMinBufferSize (int sampleRateInHz, 
                int channelConfig, 
                int audioFormat)

Returns the minimum buffer size required for the successful creation of an AudioRecord object, in byte units. Note that this size doesn't guarantee a smooth recording under load, and higher values should be chosen according to the expected frequency at which the AudioRecord instance will be polled for new data. See AudioRecord(int, int, int, int, int) for more information on valid configuration values.

Parameters
sampleRateInHz int: the sample rate expressed in Hertz. AudioFormat#SAMPLE_RATE_UNSPECIFIED is not permitted.

channelConfig int: describes the configuration of the audio channels. See AudioFormat#CHANNEL_IN_MONO and AudioFormat#CHANNEL_IN_STEREO

audioFormat int: the format in which the audio data is represented. See AudioFormat#ENCODING_PCM_16BIT.

Returns
int ERROR_BAD_VALUE if the recording parameters are not supported by the hardware, or an invalid parameter was passed, or ERROR if the implementation was unable to query the hardware for its input properties, or the minimum buffer size expressed in bytes.

getNotificationMarkerPosition

Added in API level 3
public int getNotificationMarkerPosition ()

Returns the notification marker position expressed in frames.

Returns
int

getPositionNotificationPeriod

Added in API level 3
public int getPositionNotificationPeriod ()

Returns the notification update period expressed in frames.

Returns
int

getPreferredDevice

Added in API level 23
public AudioDeviceInfo getPreferredDevice ()

Returns the selected input specified by setPreferredDevice(AudioDeviceInfo). Note that this is not guarenteed to correspond to the actual device being used for recording.

Returns
AudioDeviceInfo

getRecordingState

Added in API level 3
public int getRecordingState ()

Returns the recording state of the AudioRecord instance.

Returns
int

getRoutedDevice

Added in API level 23
public AudioDeviceInfo getRoutedDevice ()

Returns an AudioDeviceInfo identifying the current routing of this AudioRecord. Note: The query is only valid if the AudioRecord is currently recording. If it is not, getRoutedDevice() will return null.

Returns
AudioDeviceInfo

getSampleRate

Added in API level 3
public int getSampleRate ()

Returns the configured audio sink sample rate in Hz. The sink sample rate never changes after construction. If the constructor had a specific sample rate, then the sink sample rate is that value. If the constructor had AudioFormat#SAMPLE_RATE_UNSPECIFIED, then the sink sample rate is a route-dependent default value based on the source [sic].

Returns
int

getState

Added in API level 3
public int getState ()

Returns the state of the AudioRecord instance. This is useful after the AudioRecord instance has been created to check if it was initialized properly. This ensures that the appropriate hardware resources have been acquired.

Returns
int

getTimestamp

Added in API level 24
public int getTimestamp (AudioTimestamp outTimestamp, 
                int timebase)

Poll for an AudioTimestamp on demand.

The AudioTimestamp reflects the frame delivery information at the earliest point available in the capture pipeline.

Calling startRecording() following a stop() will reset the frame count to 0.

Parameters
outTimestamp AudioTimestamp: a caller provided non-null AudioTimestamp instance, which is updated with the AudioRecord frame delivery information upon success.

timebase int: one of AudioTimestamp.TIMEBASE_BOOTTIME or AudioTimestamp.TIMEBASE_MONOTONIC, used to select the clock for the AudioTimestamp time. Value is AudioTimestamp.TIMEBASE_MONOTONIC, or AudioTimestamp.TIMEBASE_BOOTTIME

Returns
int SUCCESS if a timestamp is available, or ERROR_INVALID_OPERATION if a timestamp not available.

isPrivacySensitive

Added in API level 30
public boolean isPrivacySensitive ()

Returns whether this AudioRecord is marked as privacy sensitive or not.

See Builder#setPrivacySensitive(boolean)

Returns
boolean true if privacy sensitive, false otherwise

read

Added in API level 23
public int read (short[] audioData, 
                int offsetInShorts, 
                int sizeInShorts, 
                int readMode)

Reads audio data from the audio hardware for recording into a short array. The format specified in the AudioRecord constructor should be AudioFormat#ENCODING_PCM_16BIT to correspond to the data in the array.

Parameters
audioData short: the array to which the recorded audio data is written. This value cannot be null.

offsetInShorts int: index in audioData from which the data is written expressed in shorts. Must not be negative, or cause the data access to go out of bounds of the array.

sizeInShorts int: the number of requested shorts. Must not be negative, or cause the data access to go out of bounds of the array.

readMode int: one of READ_BLOCKING, READ_NON_BLOCKING.
With READ_BLOCKING, the read will block until all the requested data is read.
With READ_NON_BLOCKING, the read will return immediately after reading as much audio data as possible without blocking. Value is READ_BLOCKING, or READ_NON_BLOCKING

Returns
int zero or the positive number of shorts that were read, or one of the following error codes. The number of shorts will be a multiple of the channel count not to exceed sizeInShorts.
  • ERROR_INVALID_OPERATION if the object isn't properly initialized
  • ERROR_BAD_VALUE if the parameters don't resolve to valid data and indexes
  • ERROR_DEAD_OBJECT if the object is not valid anymore and needs to be recreated. The dead object error code is not returned if some data was successfully transferred. In this case, the error is returned at the next read()
  • ERROR in case of other error

read

Added in API level 23
public int read (ByteBuffer audioBuffer, 
                int sizeInBytes, 
                int readMode)

Reads audio data from the audio hardware for recording into a direct buffer. If this buffer is not a direct buffer, this method will always return 0. Note that the value returned by Buffer.position() on this buffer is unchanged after a call to this method. The representation of the data in the buffer will depend on the format specified in the AudioRecord constructor, and will be native endian.

Parameters
audioBuffer ByteBuffer: the direct buffer to which the recorded audio data is written. Data is written to audioBuffer.position(). This value cannot be null.

sizeInBytes int: the number of requested bytes. It is recommended but not enforced that the number of bytes requested be a multiple of the frame size (sample size in bytes multiplied by the channel count).

readMode int: one of READ_BLOCKING, READ_NON_BLOCKING.
With READ_BLOCKING, the read will block until all the requested data is read.
With READ_NON_BLOCKING, the read will return immediately after reading as much audio data as possible without blocking. Value is READ_BLOCKING, or READ_NON_BLOCKING

Returns
int zero or the positive number of bytes that were read, or one of the following error codes. The number of bytes will not exceed sizeInBytes and will be truncated to be a multiple of the frame size.
  • ERROR_INVALID_OPERATION if the object isn't properly initialized
  • ERROR_BAD_VALUE if the parameters don't resolve to valid data and indexes
  • ERROR_DEAD_OBJECT if the object is not valid anymore and needs to be recreated. The dead object error code is not returned if some data was successfully transferred. In this case, the error is returned at the next read()
  • ERROR in case of other error

read

Added in API level 3
public int read (short[] audioData, 
                int offsetInShorts, 
                int sizeInShorts)

Reads audio data from the audio hardware for recording into a short array. The format specified in the AudioRecord constructor should be AudioFormat#ENCODING_PCM_16BIT to correspond to the data in the array.

Parameters
audioData short: the array to which the recorded audio data is written. This value cannot be null.

offsetInShorts int: index in audioData to which the data is written expressed in shorts. Must not be negative, or cause the data access to go out of bounds of the array.

sizeInShorts int: the number of requested shorts. Must not be negative, or cause the data access to go out of bounds of the array.

Returns
int zero or the positive number of shorts that were read, or one of the following error codes. The number of shorts will be a multiple of the channel count not to exceed sizeInShorts.
  • ERROR_INVALID_OPERATION if the object isn't properly initialized
  • ERROR_BAD_VALUE if the parameters don't resolve to valid data and indexes
  • ERROR_DEAD_OBJECT if the object is not valid anymore and needs to be recreated. The dead object error code is not returned if some data was successfully transferred. In this case, the error is returned at the next read()
  • ERROR in case of other error

read

Added in API level 23
public int read (float[] audioData, 
                int offsetInFloats, 
                int sizeInFloats, 
                int readMode)

Reads audio data from the audio hardware for recording into a float array. The format specified in the AudioRecord constructor should be AudioFormat#ENCODING_PCM_FLOAT to correspond to the data in the array.

Parameters
audioData float: the array to which the recorded audio data is written. This value cannot be null.

offsetInFloats int: index in audioData from which the data is written. Must not be negative, or cause the data access to go out of bounds of the array.

sizeInFloats int: the number of requested floats. Must not be negative, or cause the data access to go out of bounds of the array.

readMode int: one of READ_BLOCKING, READ_NON_BLOCKING.
With READ_BLOCKING, the read will block until all the requested data is read.
With READ_NON_BLOCKING, the read will return immediately after reading as much audio data as possible without blocking. Value is READ_BLOCKING, or READ_NON_BLOCKING

Returns
int zero or the positive number of floats that were read, or one of the following error codes. The number of floats will be a multiple of the channel count not to exceed sizeInFloats.
  • ERROR_INVALID_OPERATION if the object isn't properly initialized
  • ERROR_BAD_VALUE if the parameters don't resolve to valid data and indexes
  • ERROR_DEAD_OBJECT if the object is not valid anymore and needs to be recreated. The dead object error code is not returned if some data was successfully transferred. In this case, the error is returned at the next read()
  • ERROR in case of other error

read

Added in API level 23
public int read (byte[] audioData, 
                int offsetInBytes, 
                int sizeInBytes, 
                int readMode)

Reads audio data from the audio hardware for recording into a byte array. The format specified in the AudioRecord constructor should be AudioFormat#ENCODING_PCM_8BIT to correspond to the data in the array. The format can be AudioFormat#ENCODING_PCM_16BIT, but this is deprecated.

Parameters
audioData byte: the array to which the recorded audio data is written. This value cannot be null.

offsetInBytes int: index in audioData to which the data is written expressed in bytes. Must not be negative, or cause the data access to go out of bounds of the array.

sizeInBytes int: the number of requested bytes. Must not be negative, or cause the data access to go out of bounds of the array.

readMode int: one of READ_BLOCKING, READ_NON_BLOCKING.
With READ_BLOCKING, the read will block until all the requested data is read.
With READ_NON_BLOCKING, the read will return immediately after reading as much audio data as possible without blocking. Value is READ_BLOCKING, or READ_NON_BLOCKING

Returns
int zero or the positive number of bytes that were read, or one of the following error codes. The number of bytes will be a multiple of the frame size in bytes not to exceed sizeInBytes.
  • ERROR_INVALID_OPERATION if the object isn't properly initialized
  • ERROR_BAD_VALUE if the parameters don't resolve to valid data and indexes
  • ERROR_DEAD_OBJECT if the object is not valid anymore and needs to be recreated. The dead object error code is not returned if some data was successfully transferred. In this case, the error is returned at the next read()
  • ERROR in case of other error

read

Added in API level 3
public int read (ByteBuffer audioBuffer, 
                int sizeInBytes)

Reads audio data from the audio hardware for recording into a direct buffer. If this buffer is not a direct buffer, this method will always return 0. Note that the value returned by Buffer.position() on this buffer is unchanged after a call to this method. The representation of the data in the buffer will depend on the format specified in the AudioRecord constructor, and will be native endian.

Parameters
audioBuffer ByteBuffer: the direct buffer to which the recorded audio data is written. Data is written to audioBuffer.position(). This value cannot be null.

sizeInBytes int: the number of requested bytes. It is recommended but not enforced that the number of bytes requested be a multiple of the frame size (sample size in bytes multiplied by the channel count).

Returns
int zero or the positive number of bytes that were read, or one of the following error codes. The number of bytes will not exceed sizeInBytes and will be truncated to be a multiple of the frame size.
  • ERROR_INVALID_OPERATION if the object isn't properly initialized
  • ERROR_BAD_VALUE if the parameters don't resolve to valid data and indexes
  • ERROR_DEAD_OBJECT if the object is not valid anymore and needs to be recreated. The dead object error code is not returned if some data was successfully transferred. In this case, the error is returned at the next read()
  • ERROR in case of other error

read

Added in API level 3
public int read (byte[] audioData, 
                int offsetInBytes, 
                int sizeInBytes)

Reads audio data from the audio hardware for recording into a byte array. The format specified in the AudioRecord constructor should be AudioFormat#ENCODING_PCM_8BIT to correspond to the data in the array.

Parameters
audioData byte: the array to which the recorded audio data is written. This value cannot be null.

offsetInBytes int: index in audioData from which the data is written expressed in bytes.

sizeInBytes int: the number of requested bytes.

Returns
int zero or the positive number of bytes that were read, or one of the following error codes. The number of bytes will not exceed sizeInBytes.
  • ERROR_INVALID_OPERATION if the object isn't properly initialized
  • ERROR_BAD_VALUE if the parameters don't resolve to valid data and indexes
  • ERROR_DEAD_OBJECT if the object is not valid anymore and needs to be recreated. The dead object error code is not returned if some data was successfully transferred. In this case, the error is returned at the next read()
  • ERROR in case of other error

registerAudioRecordingCallback

Added in API level 29
public void registerAudioRecordingCallback (Executor executor, 
                AudioManager.AudioRecordingCallback cb)

Register a callback to be notified of audio capture changes via a AudioManager.AudioRecordingCallback. A callback is received when the capture path configuration changes (pre-processing, format, sampling rate...) or capture is silenced/unsilenced by the system.

Parameters
executor Executor: Executor to handle the callbacks. This value cannot be null. Callback and listener events are dispatched through this Executor, providing an easy way to control which thread is used. To dispatch events through the main thread of your application, you can use Context.getMainExecutor(). Otherwise, provide an Executor that dispatches to an appropriate thread.

cb AudioManager.AudioRecordingCallback: non-null callback to register

release

Added in API level 3
public void release ()

Releases the native AudioRecord resources. The object can no longer be used and the reference should be set to null after a call to release()

removeOnRoutingChangedListener

Added in API level 23
Deprecated in API level 24
public void removeOnRoutingChangedListener (AudioRecord.OnRoutingChangedListener listener)

This method was deprecated in API level 24.
users should switch to the general purpose AudioRouting.OnRoutingChangedListener class instead.

Removes an OnRoutingChangedListener which has been previously added to receive rerouting notifications.

Parameters
listener AudioRecord.OnRoutingChangedListener: The previously added OnRoutingChangedListener interface to remove.

removeOnRoutingChangedListener

Added in API level 24
public void removeOnRoutingChangedListener (AudioRouting.OnRoutingChangedListener listener)

Removes an AudioRouting.OnRoutingChangedListener which has been previously added to receive rerouting notifications.

Parameters
listener AudioRouting.OnRoutingChangedListener: The previously added AudioRouting.OnRoutingChangedListener interface to remove.

setLogSessionId

Added in API level 31
public void setLogSessionId (LogSessionId logSessionId)

Sets a LogSessionId instance to this AudioRecord for metrics collection.

Parameters
logSessionId LogSessionId: a LogSessionId instance which is used to identify this object to the metrics service. Proper generated Ids must be obtained from the Java metrics service and should be considered opaque. Use LogSessionId#LOG_SESSION_ID_NONE to remove the logSessionId association. This value cannot be null.

Throws
IllegalStateException if AudioRecord not initialized.

setNotificationMarkerPosition

Added in API level 3
public int setNotificationMarkerPosition (int markerInFrames)

Sets the marker position at which the listener is called, if set with setRecordPositionUpdateListener(android.media.AudioRecord.OnRecordPositionUpdateListener) or setRecordPositionUpdateListener(android.media.AudioRecord.OnRecordPositionUpdateListener, android.os.Handler).

Parameters
markerInFrames int: marker position expressed in frames

Returns
int error code or success, see SUCCESS, ERROR_BAD_VALUE, ERROR_INVALID_OPERATION

setPositionNotificationPeriod

Added in API level 3
public int setPositionNotificationPeriod (int periodInFrames)

Sets the period at which the listener is called, if set with setRecordPositionUpdateListener(android.media.AudioRecord.OnRecordPositionUpdateListener) or setRecordPositionUpdateListener(android.media.AudioRecord.OnRecordPositionUpdateListener, android.os.Handler). It is possible for notifications to be lost if the period is too small.

Parameters
periodInFrames int: update period expressed in frames

Returns
int error code or success, see SUCCESS, ERROR_INVALID_OPERATION

setPreferredDevice

Added in API level 23
public boolean setPreferredDevice (AudioDeviceInfo deviceInfo)

Specifies an audio device (via an AudioDeviceInfo object) to route the input to this AudioRecord.

Parameters
deviceInfo AudioDeviceInfo: The AudioDeviceInfo specifying the audio source. If deviceInfo is null, default routing is restored.

Returns
boolean true if successful, false if the specified AudioDeviceInfo is non-null and does not correspond to a valid audio input device.

setPreferredMicrophoneDirection

Added in API level 29
public boolean setPreferredMicrophoneDirection (int direction)

Specifies the logical microphone (for processing). Applications can use this to specify which side of the device to optimize capture from. Typically used in conjunction with the camera capturing video.

Parameters
direction int: Value is MicrophoneDirection.MIC_DIRECTION_UNSPECIFIED, MicrophoneDirection.MIC_DIRECTION_TOWARDS_USER, MicrophoneDirection.MIC_DIRECTION_AWAY_FROM_USER, or MicrophoneDirection.MIC_DIRECTION_EXTERNAL

Returns
boolean true if sucessful.

setPreferredMicrophoneFieldDimension

Added in API level 29
public boolean setPreferredMicrophoneFieldDimension (float zoom)

Specifies the zoom factor (i.e. the field dimension) for the selected microphone (for processing). The selected microphone is determined by the use-case for the stream.

Parameters
zoom float: the desired field dimension of microphone capture. Range is from -1 (wide angle), though 0 (no zoom) to 1 (maximum zoom). Value is between -1.0 and 1.0 inclusive

Returns
boolean true if sucessful.

setRecordPositionUpdateListener

Added in API level 3
public void setRecordPositionUpdateListener (AudioRecord.OnRecordPositionUpdateListener listener)

Sets the listener the AudioRecord notifies when a previously set marker is reached or for each periodic record head position update.

setRecordPositionUpdateListener

Added in API level 3
public void setRecordPositionUpdateListener (AudioRecord.OnRecordPositionUpdateListener listener, 
                Handler handler)

Sets the listener the AudioRecord notifies when a previously set marker is reached or for each periodic record head position update. Use this method to receive AudioRecord events in the Handler associated with another thread than the one in which you created the AudioRecord instance.

Parameters
handler Handler: the Handler that will receive the event notification messages.

startRecording

Added in API level 16
public void startRecording (MediaSyncEvent syncEvent)

Starts recording from the AudioRecord instance when the specified synchronization event occurs on the specified audio session.

Parameters
syncEvent MediaSyncEvent: event that triggers the capture.

Throws
java.lang.IllegalStateException
IllegalStateException

See also:

startRecording

Added in API level 3
public void startRecording ()

Starts recording from the AudioRecord instance.

Throws
java.lang.IllegalStateException
IllegalStateException

stop

Added in API level 3
public void stop ()

Stops recording.

Throws
java.lang.IllegalStateException
IllegalStateException

unregisterAudioRecordingCallback

Added in API level 29
public void unregisterAudioRecordingCallback (AudioManager.AudioRecordingCallback cb)

Unregister an audio recording callback previously registered with registerAudioRecordingCallback(java.util.concurrent.Executor, android.media.AudioManager.AudioRecordingCallback).

Parameters
cb AudioManager.AudioRecordingCallback: non-null callback to unregister

Protected methods

finalize

Added in API level 3
protected void finalize ()

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.

The general contract of finalize is that it is invoked if and when the Java virtual machine has determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, except as a result of an action taken by the finalization of some other object or class which is ready to be finalized. The finalize method may take any action, including making this object available again to other threads; the usual purpose of finalize, however, is to perform cleanup actions before the object is irrevocably discarded. For example, the finalize method for an object that represents an input/output connection might perform explicit I/O transactions to break the connection before the object is permanently discarded.

The finalize method of class Object performs no special action; it simply returns normally. Subclasses of Object may override this definition.

The Java programming language does not guarantee which thread will invoke the finalize method for any given object. It is guaranteed, however, that the thread that invokes finalize will not be holding any user-visible synchronization locks when finalize is invoked. If an uncaught exception is thrown by the finalize method, the exception is ignored and finalization of that object terminates.

After the finalize method has been invoked for an object, no further action is taken until the Java virtual machine has again determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, including possible actions by other objects or classes which are ready to be finalized, at which point the object may be discarded.

The finalize method is never invoked more than once by a Java virtual machine for any given object.

Any exception thrown by the finalize method causes the finalization of this object to be halted, but is otherwise ignored.