Search code examples
androidrecordaudiorecord

split two channels of AudioRecord of CHANNEL_IN_STEREO


I'm working on a project using stereo record of the Android phones (note 3). But I need to split the data from different channels (right, left). Any idea of how to perform that?

Now, I use AudioRecord to record the sound of internal microphones. And I can record, save the sound to .raw and .wav files.

Some codes as follows.

private int audioSource = MediaRecorder.AudioSource.MIC;  
private static int sampleRateInHz = 44100;  
private static int channelConfig = AudioFormat.CHANNEL_IN_STEREO;  
private static int audioFormat = AudioFormat.ENCODING_PCM_16BIT;


bufferSizeInBytes = AudioRecord.getMinBufferSize(sampleRateInHz,  
            channelConfig, audioFormat);  

audioRecord = new AudioRecord(audioSource, sampleRateInHz,  
            channelConfig, audioFormat, bufferSizeInBytes);

// some other codes....

//get the data from audioRecord
readsize = audioRecord.read(audiodata, 0, bufferSizeInBytes); 

Solution

  • Finally, I got the answers. I used stereo record of android phone. And the audioFormat is PCM_16BIT.

    private int audioSource = MediaRecorder.AudioSource.MIC;  
    private static int sampleRateInHz = 48000;  
    private static int channelConfig = AudioFormat.CHANNEL_IN_STEREO;  
    private static int audioFormat = AudioFormat.ENCODING_PCM_16BIT;  
    

    which means the data stored in buffer as follows.

    leftChannel data: [0,1],[4,5]...
    rightChannel data: [2,3],[6,7]...
    

    So the code of splitting data of stereo record.

    readSize = audioRecord.read(audioShortData, 0, bufferSizeInBytes);
    for(int i = 0; i < readSize/2; i = i + 2)
    {
           leftChannelAudioData[i] = audiodata[2*i];
           leftChannelAudioData[i+1] = audiodata[2*i+1]; 
           rightChannelAudioData[i] =  audiodata[2*i+2];
           rightChannelAudioData[i+1] = audiodata[2*i+3];
    }
    

    Then you can write the data to file.

    leftChannelFos = new FileOutputStream(rawLeftChannelDataFile);
    rightChannelFos = new FileOutputStream(rawRightChannelDataFile);
    leftChannelBos = new BufferedOutputStream(leftChannelFos);
    rightChannelBos = new BufferedOutputStream(rightChannelFos);
    leftChannelDos = new DataOutputStream(leftChannelBos);
    rightChannelDos = new  DataOutputStream(rightChannelBos);
    
    leftChannelDos.write(leftChannelAudioData);
    rightChannelDos.write(rightChannelAudioData);
    

    Happy coding!