【发布时间】:2020-08-08 01:50:30
【问题描述】:
我无法在 C++ 中的 16 位缩放 PCM 数据和浮点 PCM 数据之间进行转换。我想我一定很接近,因为输出的音频有点像我的预期,但它是失真的。
我这样做的原因是因为我在浏览器中运行 ScummVM 游戏。 ScummVM 代码在服务器上运行,我的自定义代码将音频和图像发布到网站。我正在使用“Web-Audio Api”在前端的 JavaScript 中播放声音。
我正在尝试向 JavaScript 提供按通道分段的原始 PCM 数据。我的逻辑是,如果不需要解码,延迟会更短。
我知道音频数据一定是好的,因为我已经成功将这个转换成wave文件格式播放了。
我正在尝试获取一个多维浮点数组。第一个维度代表通道,第二个维度是该通道的样本数据。
我要求我们不要讨论该项目的实用性。这对我来说是一个学习项目,而不是试图构建一个广泛使用的产品。
这是我的算法,cmets 描述了我的推理。
C++ 端
typedef unsigned char byte;
double** OSystem_Cli::mixCallback(uint len)
{
const int NO_CHANNELS = 2;
double** result = new double*[NO_CHANNELS];
int sampleSize = len;
byte* samples = new byte[len];
_mixerImpl->mixCallback(samples, len); //Get the 16-bit PCM audio from Scumm VM. eg. [91,11,91,11 . . .] and stores it in samples
for (int channel = 0; channel < NO_CHANNELS; channel++)
{
for (int byteNo = channel * 2, channelByteNo = 0; byteNo < sampleSize - 1; byteNo = byteNo + NO_CHANNELS * 2, channelByteNo++)
{
if (channelByteNo == 0)
{
result[channel] = new double[sampleSize / NO_CHANNELS / 2];
}
unsigned short unsignedCombination = (static_cast<unsigned short>(samples[byteNo]) << 8) + samples[byteNo + 1]; //Join two bytes together to get 1 sixteen bit number.
short signedCombination;
memcpy(&signedCombination, &unsignedCombination, sizeof(signedCombination));
double signedFloat = static_cast<double>(signedCombination);
signedFloat = signedFloat / (float)32768; //Divide it to get the floating point representation, as https://stackoverflow.com/questions/15087668/how-to-convert-pcm-samples-in-byte-array-as-floating-point-numbers-in-the-range states.
if (signedFloat > 1)
{
signedFloat = 1;
}
else if (signedFloat < -1)
{
signedFloat = -1;
}
result[channel][channelByteNo] = signedFloat;
}
}
delete[] samples;
return result;
}
JavaScript 端(在类型脚本中):
pushOntoAudioQueue(pcmBytesByChannel: number[][]) {
const streamer: WebAudioStreamer = this;
const samplePartsPerChannel = pcmBytesByChannel[0].length;
const noChannels = pcmBytesByChannel.length;
if (this.audioStack.length > MaxQueueLength) {
this.audioStack = [];
}
const buffer = this.context.createBuffer(noChannels, samplePartsPerChannel, 16000); //Length is total number of bytes for all channels
for (let channel = 0; channel < noChannels; channel++) {
let float32ChannelData = new Float32Array(pcmBytesByChannel[channel].length);
float32ChannelData.set(pcmBytesByChannel[channel]);
buffer.copyToChannel(float32ChannelData, channel);
}
streamer.audioQueue.push(buffer);
}
【问题讨论】:
-
cli::array<cli::array<double>^>^ result-- 这不是 C++。 -
这是托管数组的 C++ CLI 表示法。 C++ CLI 是微软世界中托管和非托管代码之间的桥梁。正如我在评论中所说,将其视为双 [] []。 C++ CLI 部分对这个问题几乎没有影响。数字运算仍然有效。
-
有一个标签。仅仅标记 C++ 是一种误导。
标签: javascript c++ audio html5-audio pcm