Skip to content

Instantly share code, notes, and snippets.

@nalitzis
Created June 2, 2012 09:34
Show Gist options
  • Save nalitzis/2857519 to your computer and use it in GitHub Desktop.
Save nalitzis/2857519 to your computer and use it in GitHub Desktop.
Audio record
public static final int FREQUENCY = 44100;
public static final int CHANNEL_CONFIGURATION = AudioFormat.CHANNEL_CONFIGURATION_MONO;
public static final int AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
private void recordSound(){
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/"+RECORDED_FILENAME);
// Delete any previous recording.
if (file.exists())
file.delete();
try {
file.createNewFile();
// Create a DataOuputStream to write the audio data into the saved file.
OutputStream os = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(os);
DataOutputStream dos = new DataOutputStream(bos);
// Create a new AudioRecord object to record the audio.
int bufferSize = AudioRecord.getMinBufferSize(FREQUENCY, CHANNEL_CONFIGURATION, AUDIO_ENCODING);
AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, FREQUENCY, CHANNEL_CONFIGURATION, AUDIO_ENCODING, bufferSize);
short[] buffer = new short[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();
audioRecord.release();
dos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment