Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android How To record audio using MediaRecorder and output as raw PCM?

I currently record audio using MediaRecorder to produce .m4a, .mp4, .acc and .3gp, and also visualize the output data of each recording with VisualizerView.

Now I would like to do the same thing with PCM.

I have tried using MediaRecorder with ENCODING_PCM_16BIT input with several different combinations of output. But none of the combinations produce raw PCM output.

My question is: How can I record using MediaRecorder and output the result as raw PCM?

Java code:

public String mFileName = null;
private String fileName = null;
private String fileNamePcm = null;

String formattedDate = new SimpleDateFormat("MM-dd-yyyy_HH-mm-ss").format(new Date());
fileName = formattedDate;
fileNamePcm = formattedDate;

MediaRecorder mRecorder = new MediaRecorder();

startRecording() {

    // Test Format 1 - produced AMR_WB file
    mRecorder.setAudioSamplingRate(44100);
    mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mRecorder.setOutputFormat(AudioFormat.CHANNEL_OUT_MONO); // produced AMR_WB file.
    mRecorder.setAudioEncoder(AudioFormat.ENCODING_PCM_16BIT);


    // Test Format 2 - produced 3gp file
    mRecorder.setAudioSamplingRate(44100);
    mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT); // produced 3gp file.
    mRecorder.setAudioEncoder(AudioFormat.ENCODING_PCM_16BIT);


    // Test Format 3 - produced 3gp file
    mRecorder.setAudioSamplingRate(44100);
    mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT); // did not produced a file.
    mRecorder.setAudioEncoder(AudioFormat.ENCODING_PCM_16BIT);
    mRecorder.setOutputFile(fileNamePcm);  // produced 3gp file. // trying to write raw pcm output to file.


    mFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "TestRecordings" + "/" + fileName + ".3gp";
    mFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "TestRecordings" + "/" + fileNamePcm + ".pcm";

    mRecorder.setOutputFile(mFileName);

    try {
        mRecorder.prepare();
    } catch (IOException e) {
        Log.e(LOG_TAG, "prepare() failed");
    } catch (IllegalStateException e) {
        e.printStackTrace();
    }

    mRecorder.start();

}
like image 338
user2308699 Avatar asked Jun 14 '17 22:06

user2308699


1 Answers

To get raw PCM data, you will have to use AudioRecord class - it supports ENCODING_PCM_8BIT, ENCODING_PCM_16BIT, and ENCODING_PCM_FLOAT.

like image 72
Filip Kwiatkowski Avatar answered Oct 19 '22 16:10

Filip Kwiatkowski