我收到一个字符串,表示来自通过getUserMedia捕获的浏览器的音频样本数组。 getUserMedia以48000记录,在将字符串值发送到服务器之前,我正在交错2个通道。我将这个字符串转换为float [],如下所示:
string[] raw = buffer.ToString().Split(new char[]{ ',' });
float[] fArray = new float[raw.Length];
for (int x = 0; x < raw.Length; x++)
{
float sampleVal = float.Parse(raw[x]);
fArray[x] = sampleVal;
}
我想要做的是将float []数组转换为byte []数组,以便我可以将它传递给BufferedWaveProvider(48000,16,1)进行回放。以下是我目前正在尝试进行转换的方式:
byte[] bSamples = new byte[fArray.Length * 2];
for (int x = 0; x < fArray.Length; x += 2)
{
short sSample = (short)Math.Floor(fArray[x] * 32767);
byte[] tmp = BitConverter.GetBytes(sSample);
bSamples[x] = tmp[0];
bSamples[x + 1] = tmp[1];
}
使用上面的代码,只会产生垃圾。有人能指出我做正确的转换吗?
我已经看过this,但它并没有让我到达我需要去的地方。
答案 0 :(得分:0)
看起来您的索引在第二个循环中并不完全正确。您正在循环float
个样本,并在short
输出中使用相同的索引:
for (int x = 0; x < fArray.Length; x += 2)
另一件事(让我们假设浮点输入是真正的IEEE 32位浮点样本,在[-1.0,1.0]范围内,所以我们不用担心转换)。是立体声输入吗?如果是这样,那么您需要在转换为&#39; short&#39;之前合并样本。这很容易做到。只需平均连续成对的float
值(左声道/右声道)。
输出数组的大小应该是正确的。从技术上讲,它是这样的:
int inchannels = 2; // doesn't have to be a variable, but shows 'stereo' input.
int numsamples = fArray.Length / inchannels;
byte [] bSamples = new byte [numsamples * sizeof(Int16)];
然后您应该能够按如下方式进行转换。请注意,这假设是立体声输入,因此它会对浮点样本求平均值。
int outindex = 0;
for( int inindex = 0; inindex < fArray.Length; inindex += 2 )
{
// 'insample' is the average of left and right channels. This isn't
// entirely accurate - if one channel is 0.0, then we should just use
// the other channel verbatim. But this is close enough.
float insample = (fArray[inindex] + fArray[inindex+1]) / 2.0f;
// The output sample. It's probably better to use Int16.MaxValue
// than the hard-coded value.
Int16 outsample = (Int16)(insample * (float)Int16.MaxValue);
// I'm old-school, so I'm a fan of 'unsafe'. But you can use the
// BitConverter that you were already using. Actually, I would've
// probably done this entire conversion in 'unsafe' mode.
unsafe
{
fixed( byte * pbyte = &bSamples[outindex] )
{
Int16 * p = (Int16 *)pbyte;
*p = outsample;
outindex += sizeof(Int16);
}
}
}
答案 1 :(得分:0)
为时已晚,但仍然有用 - 我已将float[] samples
数组中的转换代码发布到byte[]
数组https://stackoverflow.com/a/42151979/4778700