我正在尝试使用libopus对来自硬件的传入pcm数据进行编码,然后使用相同的库对其进行解码,但我得到的结果是decoded.raw
可以使用aplay -t raw --rate=48000 --buffer-size=1920 --channels=1 --format=FLOAT_LE decoded.raw
命令来播放,但它是还是只是白噪声。 test.raw
文件可以使用相同的上一个命令播放,没问题。但是test.opus
文件无法以任何方式播放。不知道我在这里缺少什么,数据在test.raw
写得很好所以我认为这不是记录策略的问题。
#include <string>
#include <AL/al.h>
#include <AL/alc.h>
#include <AL/alext.h>
#include <opus/opus.h>
#include <string.h>
int main() {
FILE* raw = fopen("test.raw", "w");
FILE* opus = fopen("test.opus", "w");
FILE* decoded = fopen("decoded.raw", "w");
int i = 0;
size_t capture_frequency = 48000;
size_t samples_size = capture_frequency/25;
int channels_length = 1;
int error;
OpusEncoder* encoder = opus_encoder_create(capture_frequency, 1, OPUS_APPLICATION_VOIP, &error);
if(error != OPUS_OK){
fprintf(stderr, "failed to create codec\n");
}
const ALCchar* deviceName = alcGetString(NULL, ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER);
ALCdevice* device = alcCaptureOpenDevice(deviceName, capture_frequency, AL_FORMAT_MONO_FLOAT32, samples_size);
if(device == NULL) {
fprintf(stderr, "could not open device\n");
return -1;
}
printf("Opened capture device \"%s\"\n", alcGetString(device, ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER));
alcCaptureStart(device);
OpusDecoder* decoder = opus_decoder_create(capture_frequency, channels_length, &error);
if(error != OPUS_OK)
fprintf(stderr, "failed to create decoder\n");
while(alcGetError(device) == ALC_NO_ERROR && i < 1000){
ALCint availableSamples = 0;
alcGetIntegerv(device, ALC_CAPTURE_SAMPLES, 1, &availableSamples);
if(availableSamples < samples_size)
continue;
float* buffer = (float*)malloc(samples_size*channels_length*sizeof(float));
alcCaptureSamples(device, buffer, samples_size);
printf("got %d samples, we needed %d\n", samples_size, samples_size);
unsigned char* output = (unsigned char*) malloc(4000);
int bytes_written = opus_encode_float(encoder, buffer, samples_size, output, 4000);
if(bytes_written < 0){
if(bytes_written == OPUS_BAD_ARG)
fprintf(stderr, "invalid args\n");
else
fprintf(stderr, "failed to encode\n");
continue;
} else {
printf("got output from encoder %d\n", bytes_written);
}
fwrite(output, bytes_written, 1, opus);
float* output_pcm = (float*) malloc(samples_size*sizeof(float));
int decoded_bytes = opus_decode_float(decoder, output, bytes_written, output_pcm, samples_size, 1);
if(decoded_bytes < 1)
fprintf(stderr, "failed to decode bytes\n");
else {
printf("%d bytes decoded\n", decoded_bytes);
}
fwrite(output_pcm, samples_size*sizeof(float), 1, decoded);
fwrite(buffer, samples_size*sizeof(float), 1, raw);
i++;
}
fclose(opus);
fclose(raw);
fclose(decoded);
alcCaptureStop(device);
alcCaptureCloseDevice(device);
opus_decoder_destroy(decoder);
opus_encoder_destroy(encoder);
}
答案 0 :(得分:2)
你无法解码file.opus,因为你需要一些OPUS编解码器的容器。这很重要,因为OPUS是面向数据包的格式。所以它无法解码字节流。它可以解码数据包流。
当您逐个将数据包写入文件时,您会丢失数据包边界,并且无法恢复它们。
您可以选择以下可能的格式之一:
我认为您可以轻松找到方便的库来编写它们。