Android Audiorecord Example

android AudioRecord class to record an audio and play it back

I would like to answer my question by myself.

In the above code, recordAndPlay method, records and plays the sound simultaneously.

I splitted the code. I recorded the voice and got it stored it to the file first and then played the voice by opening the stored file and processing it.

    private void startRecording() {
final int CHANNELCONFIG = AudioFormat.CHANNEL_IN_MONO;
String filename = getTempFilename();
OutputStream os = null;

try {
os = new FileOutputStream(filename);
} catch(FileNotFoundException e) {
e.printStackTrace();
}

bufferSize = AudioRecord.getMinBufferSize(FREQUENCY,CHANNELCONFIG,AUDIO_FORMAT);
audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,FREQUENCY,CHANNELCONFIG,AUDIO_FORMAT,bufferSize);

audioData = new byte[bufferSize];

audioRecord.startRecording();

int read = 0;

while (recording) {
read = audioRecord.read(audioData,0,bufferSize);
if(AudioRecord.ERROR_INVALID_OPERATION != read){
try {
os.write(audioData);
} catch (IOException e) {
e.printStackTrace();
}
}
}

try {
os.close();
} catch (IOException io) {
io.printStackTrace();
}

}

private void playRecording() {

String fileName = getFilename();
File file = new File(fileName);

byte[] audioData = null;

try {
InputStream inputStream = new FileInputStream(fileName);

int minBufferSize = AudioTrack.getMinBufferSize(44100,AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
audioData = new byte[minBufferSize];

AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,FREQUENCY,AudioFormat.CHANNEL_OUT_MONO,AUDI O_FORMAT,minBufferSize,AudioTrack.MODE_STREAM);
audioTrack.play();
int i=0;

while((i = inputStream.read(audioData)) != -1) {
audioTrack.write(audioData,0,i);
}

} catch(FileNotFoundException fe) {
Log.e(LOG_TAG,"File not found");
} catch(IOException io) {
Log.e(LOG_TAG,"IO Exception");
}
}

How to record audio using AudioRecorder in Android

Try This.....

public class Audio_Record extends Activity {
private static final int RECORDER_SAMPLERATE = 8000;
private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO;
private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
private AudioRecord recorder = null;
private Thread recordingThread = null;
private boolean isRecording = false;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

setButtonHandlers();
enableButtons(false);

int bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE,
RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING);
}

private void setButtonHandlers() {
((Button) findViewById(R.id.btnStart)).setOnClickListener(btnClick);
((Button) findViewById(R.id.btnStop)).setOnClickListener(btnClick);
}

private void enableButton(int id, boolean isEnable) {
((Button) findViewById(id)).setEnabled(isEnable);
}

private void enableButtons(boolean isRecording) {
enableButton(R.id.btnStart, !isRecording);
enableButton(R.id.btnStop, isRecording);
}

int BufferElements2Rec = 1024; // want to play 2048 (2K) since 2 bytes we use only 1024
int BytesPerElement = 2; // 2 bytes in 16bit format

private void startRecording() {

recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
RECORDER_SAMPLERATE, RECORDER_CHANNELS,
RECORDER_AUDIO_ENCODING, BufferElements2Rec * BytesPerElement);

recorder.startRecording();
isRecording = true;
recordingThread = new Thread(new Runnable() {
public void run() {
writeAudioDataToFile();
}
}, "AudioRecorder Thread");
recordingThread.start();
}

//convert short to byte
private byte[] short2byte(short[] sData) {
int shortArrsize = sData.length;
byte[] bytes = new byte[shortArrsize * 2];
for (int i = 0; i < shortArrsize; i++) {
bytes[i * 2] = (byte) (sData[i] & 0x00FF);
bytes[(i * 2) + 1] = (byte) (sData[i] >> 8);
sData[i] = 0;
}
return bytes;

}

private void writeAudioDataToFile() {
// Write the output audio in byte

String filePath = "/sdcard/voice8K16bitmono.pcm";
short sData[] = new short[BufferElements2Rec];

FileOutputStream os = null;
try {
os = new FileOutputStream(filePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}

while (isRecording) {
// gets the voice output from microphone to byte format

recorder.read(sData, 0, BufferElements2Rec);
System.out.println("Short wirting to file" + sData.toString());
try {
// // writes the data to file from buffer
// // stores the voice buffer
byte bData[] = short2byte(sData);
os.write(bData, 0, BufferElements2Rec * BytesPerElement);
} catch (IOException e) {
e.printStackTrace();
}
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}

private void stopRecording() {
// stops the recording activity
if (null != recorder) {
isRecording = false;
recorder.stop();
recorder.release();
recorder = null;
recordingThread = null;
}
}

private View.OnClickListener btnClick = new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStart: {
enableButtons(true);
startRecording();
break;
}
case R.id.btnStop: {
enableButtons(false);
stopRecording();
break;
}
}
}
};

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
finish();
}
return super.onKeyDown(keyCode, event);
}
}

Recording .Wav with Android AudioRecorder

PCMAudioHelper solved my problem. I'll modify this answer and explain it but firstly i have to do some tests over this class.

Android Audio Record to wav

The only difference between a PCM file and a WAV file is that the PCM file has no header and the WAV file does. The WAV header has key information for playback such as sample rate, number of bits per sample and number of channels. When you load a PCM file either the app has to have prior knowledge of this information or you have to tell it. If you load a PCM file into audacity, for example, it will prompt you to fill in all of that stuff.

In order to make the existing save file a .WAV you need to prepend an appropriate header. I'm not going to go into details about it because there are already many answers on SO detailing it and it is readily available on the web (https://en.wikipedia.org/wiki/WAV)

The second issue you raise about the file length might have something to do with the fact that AudioRecord.read returns an int which is the number of samples actually read as it may be less than you asked for. This is really a second question though

Android AudioRecord and MediaRecorder

Using AudioRecord is the right way to go if you need to do any kind of processing. To play it back, you have a couple options. If you're only going to be playing it back in your app, you can use AudioTrack instead of MediaPlayer to play raw PCM streams.

If you want it to be playable with other applications, you'll need to convert it to something else first. WAV is normally the simplest, since you just need to add the header. You can also find libraries for converting to other formats, like JOrbis for OGG, or JLayer for MP3, etc.

Android AudioRecord - Record Audio with small file size

Actually with AudioRecord class you get raw data from sound source without any compression to byte buffer you work with and MediaRecorder class provides only basic functionality for recording media from any available sources without direct access to data buffers.

I assume you should use AudioRecord for capturing audio, apply your byte to byte task for data in AudioRecord buffer and then write modified data from buffer using compression to a file. As I remember, there is no already implemented functionality in android API for audio compression, so you should use third-party library (for example lame) or write compression yourself. You can check this sources for audio recording in MP3 with lame: https://github.com/yhirano/Mp3VoiceRecorderSampleForAndroid

Android AudioRecord/AudioTrack: Playing recording from buffer

Remove stop recording !!

   track.play();

while(isRunning)
{
buffer = new Byte[mBufferSize];

recorder.read(buffer, 0, buffer.length);

track.write(buffer, 0, buffer.length);

for (int i = 0; i <minBufferSize; i++) {
Log.d(TAG,"data " + i + " content : " + buffer[i]);
}
}

even if you want stop recording put it after reading..



Related Topics



Leave a reply



Submit