Skip to content

Most visited

Recently visited

navigation
Added in API level 3

AudioRecord

public class AudioRecord
extends Object

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

Summary

Nested classes

class AudioRecord.Builder

Builder class for AudioRecord objects. 

interface AudioRecord.OnRecordPositionUpdateListener

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

interface AudioRecord.OnRoutingChangedListener

Defines the interface by which applications can receive notifications of routing changes for the associated AudioRecord

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

Public constructors

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

Class constructor.

Public methods

void addOnRoutingChangedListener(AudioRecord.OnRoutingChangedListener listener, Handler handler)

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

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.

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 data sample rate in Hz

int getState()

Returns the state of the AudioRecord instance.

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

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

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

Reads audio data from the audio hardware for recording into a byte 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(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(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.

void release()

Releases the native AudioRecord resources.

void removeOnRoutingChangedListener(AudioRecord.OnRoutingChangedListener listener)

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

int setNotificationMarkerPosition(int markerInFrames)

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

int setPositionNotificationPeriod(int periodInFrames)

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

boolean setPreferredDevice(AudioDeviceInfo deviceInfo)

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

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 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 startRecording()

Starts recording from the AudioRecord instance.

void startRecording(MediaSyncEvent syncEvent)

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

void stop()

Stops recording.

Protected methods

void finalize()

Invoked when the garbage collector has detected that this instance is no longer reachable.

Inherited methods

From class java.lang.Object

Constants

ERROR

Added in API level 3
int ERROR

Denotes a generic operation failure.

Constant Value: -1 (0xffffffff)

ERROR_BAD_VALUE

Added in API level 3
int ERROR_BAD_VALUE

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

Constant Value: -2 (0xfffffffe)

ERROR_INVALID_OPERATION

Added in API level 3
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
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
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
int RECORDSTATE_RECORDING

indicates AudioRecord recording state is recording

Constant Value: 3 (0x00000003)

RECORDSTATE_STOPPED

Added in API level 3
int RECORDSTATE_STOPPED

indicates AudioRecord recording state is not recording

Constant Value: 1 (0x00000001)

STATE_INITIALIZED

Added in API level 3
int STATE_INITIALIZED

indicates AudioRecord state is ready to be used

Constant Value: 1 (0x00000001)

STATE_UNINITIALIZED

Added in API level 3
int STATE_UNINITIALIZED

indicates AudioRecord state is not successfully initialized.

Constant Value: 0 (0x00000000)

SUCCESS

Added in API level 3
int SUCCESS

Denotes a successful operation.

Constant Value: 0 (0x00000000)

Public constructors

AudioRecord

Added in API level 3
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.

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.
channelConfig int: describes the configuration of the audio channels. See CHANNEL_IN_MONO and CHANNEL_IN_STEREO. CHANNEL_IN_MONO is guaranteed to work on all devices.
audioFormat int: the format in which the audio data is to be returned. See ENCODING_PCM_8BIT, ENCODING_PCM_16BIT, and 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
IllegalArgumentException

Public methods

addOnRoutingChangedListener

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

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

Parameters
listener AudioRecord.OnRoutingChangedListener: The AudioRecord.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.

getAudioFormat

Added in API level 3
int getAudioFormat ()

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

Returns
int

getAudioSessionId

Added in API level 16
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
int getAudioSource ()

Returns the audio recording source.

Returns
int

See also:

getBufferSizeInFrames

Added in API level 23
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
IllegalStateException

getChannelConfiguration

Added in API level 3
int getChannelConfiguration ()

Returns the configured channel position mask.

See CHANNEL_IN_MONO and CHANNEL_IN_STEREO. This method may return 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
int getChannelCount ()

Returns the configured number of channels.

Returns
int

getFormat

Added in API level 23
AudioFormat getFormat ()

Returns the configured AudioRecord format.

Returns
AudioFormat an AudioFormat containing the AudioRecord parameters at the time of configuration.

getMinBufferSize

Added in API level 3
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.
channelConfig int: describes the configuration of the audio channels. See CHANNEL_IN_MONO and CHANNEL_IN_STEREO
audioFormat int: the format in which the audio data is represented. See 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.

See also:

getNotificationMarkerPosition

Added in API level 3
int getNotificationMarkerPosition ()

Returns the notification marker position expressed in frames.

Returns
int

getPositionNotificationPeriod

Added in API level 3
int getPositionNotificationPeriod ()

Returns the notification update period expressed in frames.

Returns
int

getPreferredDevice

Added in API level 23
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
int getRecordingState ()

Returns the recording state of the AudioRecord instance.

Returns
int

See also:

getRoutedDevice

Added in API level 23
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
int getSampleRate ()

Returns the configured audio data sample rate in Hz

Returns
int

getState

Added in API level 3
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

See also:

read

Added in API level 3
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 ENCODING_PCM_16BIT to correspond to the data in the array.

Parameters
audioData short: the array to which the recorded audio data is written.
offsetInShorts int: index in audioData from which the data is written expressed in shorts.
sizeInShorts int: the number of requested shorts.
Returns
int the number of shorts that were read 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. The number of shorts will not exceed sizeInShorts.

read

Added in API level 3
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 ENCODING_PCM_8BIT to correspond to the data in the array.

Parameters
audioData byte: the array to which the recorded audio data is written.
offsetInBytes int: index in audioData from which the data is written expressed in bytes.
sizeInBytes int: the number of requested bytes.
Returns
int the number of bytes that were read 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. The number of bytes will not exceed sizeInBytes.

read

Added in API level 23
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 ENCODING_PCM_FLOAT to correspond to the data in the array.

Parameters
audioData float: the array to which the recorded audio data is written.
offsetInFloats int: index in audioData from which the data is written.
sizeInFloats int: the number of requested floats.
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.
Returns
int the number of floats that were read 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. The number of floats will not exceed sizeInFloats.

read

Added in API level 23
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 ENCODING_PCM_16BIT to correspond to the data in the array.

Parameters
audioData short: the array to which the recorded audio data is written.
offsetInShorts int: index in audioData from which the data is written expressed in shorts.
sizeInShorts int: the number of requested shorts.
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.
Returns
int the number of shorts that were read 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. The number of shorts will not exceed sizeInShorts.

read

Added in API level 23
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 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.
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.
Returns
int the number of bytes that were read 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. The number of bytes will not exceed sizeInBytes. The number of bytes read will truncated to be a multiple of the frame size.

read

Added in API level 23
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 ENCODING_PCM_8BIT to correspond to the data in the array.

Parameters
audioData byte: the array to which the recorded audio data is written.
offsetInBytes int: index in audioData from which the data is written expressed in bytes.
sizeInBytes int: the number of requested bytes.
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.
Returns
int the number of bytes that were read 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. The number of bytes will not exceed sizeInBytes.

read

Added in API level 3
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 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.
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 the number of bytes that were read 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. The number of bytes will not exceed sizeInBytes. The number of bytes read will truncated to be a multiple of the frame size.

release

Added in API level 3
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
void removeOnRoutingChangedListener (AudioRecord.OnRoutingChangedListener listener)

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

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

setNotificationMarkerPosition

Added in API level 3
int setNotificationMarkerPosition (int markerInFrames)

Sets the marker position at which the listener is called, if set with setRecordPositionUpdateListener(OnRecordPositionUpdateListener) or setRecordPositionUpdateListener(OnRecordPositionUpdateListener, 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
int setPositionNotificationPeriod (int periodInFrames)

Sets the period at which the listener is called, if set with setRecordPositionUpdateListener(OnRecordPositionUpdateListener) or setRecordPositionUpdateListener(OnRecordPositionUpdateListener, 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
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.

setRecordPositionUpdateListener

Added in API level 3
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.

setRecordPositionUpdateListener

Added in API level 3
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.

startRecording

Added in API level 3
void startRecording ()

Starts recording from the AudioRecord instance.

Throws
IllegalStateException

startRecording

Added in API level 16
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
IllegalStateException
IllegalStateException

See also:

stop

Added in API level 3
void stop ()

Stops recording.

Throws
IllegalStateException

Protected methods

finalize

Added in API level 3
void finalize ()

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.

This site uses cookies to store your preferences for site-specific language and display options.

Hooray!

This class requires API level or higher

This doc is hidden because your selected API level for the documentation is . You can change the documentation API level with the selector above the left navigation.

For more information about specifying the API level your app requires, read Supporting Different Platform Versions.