编写WebRTC (AudioTrackSinkInterface)原始音频到光盘

Writing WebRTC (AudioTrackSinkInterface) raw audio to disc

本文关键字:音频 光盘 原始 WebRTC AudioTrackSinkInterface 编写      更新时间:2023-10-16

我正在尝试记录由WebRTC PeerConnection MediaStream传输的音频。我添加了一个接收器到音轨,实现了AudioTrackSinkInterface。它实现了OnData方法:

void TestAudioTrackSink::OnData(const void* audio_data, int bits_per_sample, int sample_rate, size_t number_of_channels, size_t number_of_frames) {
    size_t valueCount = number_of_channels * number_of_frames;
    int16_t *_data = (int16_t*)audio_data;
    f.write((char*)&_data, sizeof(int16_t) * valueCount);
    f.flush();
}

fofstream每采样位为16,采样率为16000,通道为1,为160。

但是当我用AudaCity原始导入打开创建的文件(签名16位PCM,小端序,单声道,采样率16000)时,我没有得到有意义的音频。

我如何正确地写原始音频日期?

最后我访问了指针本身存储的数据,而不是它指向的数据,这是一个经典。我的方法的正确实现如下所示:

void TestAudioTrackSink::OnData(const void* audio_data, int bits_per_sample, int sample_rate, size_t number_of_channels, size_t number_of_frames) {
    size_t number_of_bytes = number_of_channels * number_of_frames * sizeof(int16_t); //assuming bits_per_sample is 16      
    f.write(reinterpret_cast<const char*>(audio_data), number_of_bytes);
    f.flush();
}

注意:对于更多的处理webtc本地检索和发送的音频数据,我现在检查一个自定义AudioDeviceModule。

为了给@ZoolWay添加更多的细节已经正确的答案,我在Windows平台上以二进制模式打开文件时遇到了文件损坏问题。简而言之,确保文件具有ios_base::binary标志:

std::ofstream stream(LR"(D:test.pcm)", ios_base::binary);
[...]
void TestAudioTrackSink::OnData(const void* audio_data, int bits_per_sample, int sample_rate, size_t number_of_channels, size_t number_of_frames)
{
    size_t number_of_bytes = number_of_channels * number_of_frames * sizeof(int16_t); //assuming bits_per_sample is 16      
    stream.write(reinterpret_cast<const char*>(audio_data), number_of_bytes);
    stream.flush();
}