Recording Sound with Audio Record

Use the AudioRecord class to record audio directly from the hardware buffers. Create a new Audio Record object, specifying the source, frequency, channel configuration, audio encoding, and buffer size.

int bufferSize = AudioRecord.getMinBufferSize(frequency, channelConfiguration, audioEncoding);

AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, frequency, channelConfiguration, audioEncoding, bufferSize);

For privacy reasons, Android requires that the record_audio manifest permission be included in your manifest.

<uses-permission android:name="android.permission.RECORD_AUDIO"/>

The frequency, audio encoding, and channel configuration values will affect the size and quality of the recorded audio. Note that none of this meta-data is associated with the recorded files.

When your Audio Record object is initialized, run the startRecording method to begin asynchronous recording, and use the read method to add raw audio data into the recording buffer:

audioRecord.startRecording(); while (isRecording) {

int bufferReadResult = audioRecord.read(buffer, 0, bufferSize);

Listing 11-21 records raw audio from the microphone to a file stored on the SD card. The next section will show you how to use an Audio Track to play this audio.

LISTING 11-21: Recording raw audio with Audio Record Available for download on int frequency = 11025;

Wrox.com int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO; int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;

File file = new File(Environment.getExternalStorageDirectory(), "raw.pcm");

file.createNewFile(); } catch (IOException e) {}

OutputStream os = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(os); DataOutputStream dos = new DataOutputStream(bos);

int bufferSize = AudioRecord.getMinBufferSize(frequency, channelConfiguration, audioEncoding);

short[] buffer = new short[bufferSize];

// Create a new AudioRecord object to record the audio.

AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, frequency, channelConfiguration, audioEncoding, bufferSize);

audioRecord.startRecording();

while (isRecording) {

int bufferReadResult = audioRecord.read(buffer, 0, bufferSize);

for (int i = 0; i < bufferReadResult; i++) dos.writeShort(buffer[i]);

audioRecord.stop();

Mobile Apps Made Easy

Mobile Apps Made Easy

Quick start guide to skyrocket your offline and online business success with mobile apps. If you know anything about mobile devices, you’ve probably heard that famous phrase coined by one of the mobile device’s most prolific creators proclaiming that there’s an app for pretty much everything.

Get My Free Training Guide


Responses

  • Prisco
    Is audiorecord.startrecording() asynchronous?
    6 years ago

Post a comment