问题
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