Android - AudioRecord splitting of 2 channels in channel_in_stereo

放肆的年华 提交于 2019-12-25 03:50:39

问题


I came across this link but I am not sure how to implement it split two channels of AudioRecord of CHANNEL_IN_STEREO

I want to separate the data received in the left and right channel

Below is my code

for(int i = 0; i < read/2; i = i + 2)
{
    leftChannelAudioData[i] = data[2*i];
    leftChannelAudioData[i+1] = data[2*i+1];
    rightChannelAudioData[i] =  data[2*i+2];
    rightChannelAudioData[i+1] = data[2*i+3];
}

Full source can be found here: http://pastebin.com/ntm1mHG0

I have tried from line 298 to line 322 but it does not work. It crashes my application instead :/

Thanks all!


回答1:


Your close but if you consider the case where i==read/2-1 you can see the data[2*i+2] reads beyond the end of the array. Since you are going through for samples per iteration, you need to change the for loop like so:

for(int i = 0; i < read/4; i = i + 4)
{
    leftChannelAudioData[i] = data[4*i];
    leftChannelAudioData[i+1] = data[4*i+1];
    rightChannelAudioData[i] =  data[4*i+2];
    rightChannelAudioData[i+1] = data[4*i+3];
}

But the issue now is that you are reading 2 samples for the left followed by 2 samples for the right (e.g. LLRRLLRR) but audio is normally interleaved LRLRLR.

for(int i = 0; i < read/2; i = i + 2)
{
    leftChannelAudioData[i] = data[2*i];
    rightChannelAudioData[i+1] = data[2*i+1];
}

A more robust way to work it that would work for any number of channels is something like this:

double[][] deinterleaveData(double[] samples, int numChannels)
{
   // assert(samples.length() % numChannels == 0);
   int numFrames  = samples.length() / numChannels;

   double[][] result = new double[numChannels][];
   for (int ch = 0 ; ch < numChannels ; ch++)
   {
       result[ch] = new double[numFrames];
       for (int i = 0 ; i < numFrames ; i++)
       {
           result[ch][i] = samples[numChannels*i+ch];
       }
   }
   return result;
}


来源:https://stackoverflow.com/questions/32725339/android-audiorecord-splitting-of-2-channels-in-channel-in-stereo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!