首页 > 解决方案 > 使用 libSox 链接多个效果并读取输出数据的正确方法

问题描述

我正在尝试以编程方式对 libSox 应用一些效果,但我目前无法理解我是否做得对。例如,我需要应用速度和增益效果,并在缓冲区中读取生成的音频以进行进一步处理。文档真的很稀缺,谷歌搜索没有成功。这是我的代码:

sox_format_t* input = sox_open_read("<file.wav>", NULL, NULL, NULL);
//sox_format_t* out;

sox_format_t* output = sox_open_memstream_write(&buffer, &buffer_size,
                                             &input->signal, &input->encoding, "raw", NULL);
//assert(output = sox_open_write("/home/egor/hello_processed.wav", &input->signal, NULL, NULL, NULL, NULL));
sox_effects_chain_t* chain = sox_create_effects_chain(&input->encoding, &output->encoding);

char* sox_args[10];
//input effect

sox_effect_t* e = sox_create_effect(sox_find_effect("input"));
sox_args[0] = (char*)input;
assert(sox_effect_options(e, 1, sox_args) == SOX_SUCCESS);
assert(sox_add_effect(chain, e, &input->signal, &input->signal) ==
       SOX_SUCCESS);
free(e);

e = sox_create_effect(sox_find_effect("tempo"));
std::string tempo_str = "1.01";
sox_args[0] = (char*)tempo_str.c_str();
assert(sox_effect_options(e, 1, sox_args) == SOX_SUCCESS);
assert(sox_add_effect(chain, e, &input->signal,&input->signal) ==
       SOX_SUCCESS);
free(e);


e = sox_create_effect(sox_find_effect("output"));
sox_args[0] = (char*)output;
assert(sox_effect_options(e, 1, sox_args) == SOX_SUCCESS);
assert(sox_add_effect(chain, e, &input->signal, &input->signal) ==
       SOX_SUCCESS);
free(e);
sox_flow_effects(chain, NULL, NULL);


static const size_t maxSamples=4096;
sox_sample_t samples[maxSamples];

std::vector<sox_sample_t> audio_buffer;
for (size_t r; 0 != (r=sox_read(output,samples,maxSamples));)
    for(int i=0;i<r ;i++)
        audio_buffer.push_back(samples[i]);

std::cout << audio_buffer.size() << std::endl;

我的问题是:

  1. 我是否正确设置了效果链?

  2. 如何读取内存中生成的音频样本?

    如果我使用速度值 < 1,我会从输出中获得正确数量的样本(在 audio_buffer 中),但如果我将其更改为 1.2,我会突然获得非常少量的样本,如果我使用 1.0 的值,则会获得 0。我想知道我的链配置中是否存在错误或从输出中读取数据?这是我第一次使用 libsox,我尝试按照示例进行操作,但我被困在这里。

预先感谢您的帮助!

谢谢!

标签: c++audiosoxlibsox

解决方案


  1. 您的效果链没问题,您可以通过将其写入文件来检查它是否提供了正确的输出缓冲区 - 只需在代码中替换此行:

sox_format_t* output = sox_open_memstream_write(&buffer, &buffer_size, &input->signal, &input->encoding, "raw", NULL);

对此:

sox_format_t* output = sox_open_write("2.wav", &input->signal, &input->encoding, "raw", NULL, NULL);

  1. 关于内存输出缓冲区问题 - 我研究了libsox代码,似乎它的内存缓冲区处理存在错误。作为一种解决方法,我建议您output->olength = 0;在读取output缓冲区之前添加,然后它似乎可以正常工作。

因此,您的代码将如下所示:

...
if (std::stof(tempo_str) >= 1.0) { // use workaround only if tempo >= 1.0
    output->olength = 0;
}

std::vector<sox_sample_t> audio_buffer;
for (size_t r; 0 != (r=sox_read(output,samples,maxSamples));)
    for(int i=0;i<r ;i++)
        audio_buffer.push_back(samples[i]);
...

UPD:仅在以下情况下使用解决方法tempo >= 1.0


推荐阅读