使用C++把PCM转换为MP3后,播放声音有问题,我使用的sox库,代码如下:
#include <sox.h>
//输入和输出文件路径
std::filesystem::path pcmPath(inputFilePath);
std::filesystem::path outputFilePath = pcmPath.replace_extension(".mp3");
//设置 输入音频
sox_signalinfo_t inSignalInfo;
inSignalInfo.rate = 16000;
inSignalInfo.channels = 1;
inSignalInfo.length = SOX_IGNORE_LENGTH;
//输入音频的编码信息
sox_encodinginfo_t inEncodingInfo;
inEncodingInfo.encoding = SOX_ENCODING_SIGN2;
inEncodingInfo.bits_per_sample = 16;
inEncodingInfo.compression = 1.0;
sox_format_t* inFormat = sox_open_read(inputFilePath, &inSignalInfo, &inEncodingInfo, "raw");
if (!inFormat) {
sox_quit();
return 1;
}
sox_format_t* outFormat = sox_open_write(outputFilePath.c_str(), &inFormat->signal, nullptr, "mp3", nullptr, nullptr);
if (!outFormat) {
std::cerr << "Failed to open output file." << std::endl;
sox_close(inFormat);
return 1;
}
sox_effects_chain_t* effectsChain = sox_create_effects_chain(&inFormat->encoding, &outFormat->encoding);
if (!effectsChain) {
std::cerr << "Failed to create effects chain." << std::endl;
sox_close(outFormat);
sox_close(inFormat);
return 1;
}
// Add "input" effect
sox_effect_t* inputEffect = sox_create_effect(sox_find_effect("input"));
char *inputArgs[] = {reinterpret_cast<char *>(inFormat)};
sox_effect_options(inputEffect, 1, inputArgs);
sox_add_effect(effectsChain, inputEffect, &inSignalInfo, &inSignalInfo);
// Add "output" effect
sox_effect_t* outputEffect = sox_create_effect(sox_find_effect("output"));
char *outputArgs[] = {reinterpret_cast<char *>(outFormat)};
sox_effect_options(outputEffect, 1, outputArgs);
sox_add_effect(effectsChain, outputEffect, &inSignalInfo, &inSignalInfo);
// 运行效果链
int result = sox_flow_effects(effectsChain, nullptr, nullptr);
if (result != SOX_SUCCESS) {
std::cerr << "Error during effects processing: " << sox_strerror(result) << std::endl;
// 在这里可以添加其他处理逻辑
}
// 清理资源
sox_delete_effects_chain(effectsChain);
sox_close(outFormat);
sox_close(inFormat);
std::cout << "Audio conversion successful." << std::endl;
求同学们帮忙定位原因,看下代码,是哪里没有写对呢