TransWikia.com

Recording using sox in c/c++

Stack Overflow Asked on February 18, 2021

I am trying to record sound using microphone and sox library in C/C++.

sox_open_read("default", &_input->signal, NULL, NULL)

I am trying to use default input device. I am getting the error

formats: can't open input file `default': No such file or directory

Which I guess is caused because I did not pass the last argument: filetype and sox tries to find a file with name ‘default’.
Sox lists:

  • Audio file formats: 8svx aif aifc aiff aiffc al amb au avr caf cdda cdr cvs cvsd cvu dat dvms f32 f4 f64 f8 fap flac fssd gsm gsrt hcom htk ima ircam la lpc lpc10 lu mat mat4 mat5 maud mp2 mp3 nist ogg opus paf prc pvf raw s1 s16 s2 s24 s3 s32 s4 s8 sb sd2 sds sf sl sln smp snd sndfile sndr sndt sou sox sph sw txw u1 u16 u2 u24 u3 u32 u4 u8 ub ul uw vms voc vorbis vox w64 wav wavpcm wv wve xa xi
  • audio devices drivers: alsa, oss, ossdsp

What should I pass to the sox_open_read function as the last parameter to use a microphone as an input?

One Answer

As the last parameter to sox_open_read function for microphone input, one of the audio devices drivers should be passed. In my case, it is 'alsa'.
Example:

#include <sox.h>
#include <memory>

sox_signalinfo_t _intermediateSignal;
sox_format_t* input;
sox_format_t* output;
sox_effects_chain_t* effectsChain;

void addEffect(std::string effectName, sox_format_t* options) {
    std::unique_ptr<sox_effect_t> effect(sox_create_effect(sox_find_effect(effectName.c_str())));
    char *args[] = {reinterpret_cast<char *>(options)};
    sox_effect_options(effect.get(), 1, args);
    sox_add_effect(effectsChain, effect.get(), &_intermediateSignal, &input->signal);
}

int main() {
    if (sox_init() != SOX_SUCCESS)
        throw std::runtime_error("Could not initialise SOX.");

    input = sox_open_read("default", NULL, NULL, "alsa");
    output = sox_open_write("recorded.wav", &input->signal, NULL, NULL, NULL, NULL);
    if (!input || !output)
        throw std::runtime_error("SOX I/O error");

    _intermediateSignal = input->signal;

    effectsChain = sox_create_effects_chain(&input->encoding, &output->encoding);

    if (!effectsChain)
        throw std::runtime_error("SOX could not initialize effects chain.");

    addEffect("input", input);
    addEffect("output", output);

    sox_flow_effects(effectsChain, NULL, NULL);
    sox_quit();
}

This example will never finish as sox_flow_effects call blocks the execution. Once the program is killed with ctrl+c, recorded.wav contains recorded audio.

Correct answer by Chris on February 18, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP