Search code examples
cpulseaudio

Pulseaudio C API: create a null sink


I am trying to create 2 simple programs that are basically the parec-simple and pacat-simple examples from the pulseaudio documentation. The only difference is that I would like to create a null sink, equivalent of

pactl load-module module-null-sink sink_name=steam 

(see example here) which I would then use instead of the default device on both ends - playback and record.

My question is: how can I create this null sink using pulseaudio's C API? From what I saw, pulse/simple.h does not contain any function definition to do this, so I guess I would have to use libpulse.


Solution

  • I couldn't find the pulseaudio API for it so I just use the pactl interface directly.

    For anyone interested, here is a sample code that worked for me. I just used popen to execute the pactl command to create a (null) sink:

    static bool createNullPaSink(const std::string& sinkName, int* paHandleId) {
    
        // this is the command to create the null sink with some specific setup (format, channels, rate, etc.0
        std::string pacmd = "pactl load-module module-null-sink latency_msec=100 format=s16le rate=48000 channels=2 channel_map=front-left,front-right sink_properties=device.description=QM sink_name=" + sinkName;
        // execute the pactl command
        FILE* f = popen(pacmd.c_str(), "r");
        if (!f) {
            // creating the sink failed
            return false;
        }
        
        // now get the handle of the sink by reading the output of the popen command above
        std::array<char, 128> buffer;
        std::string spaHandleId;
        while (fgets(buffer.data(), 128, f) != NULL) {
            spaHandleId += buffer.data();
        }
        auto returnCode = pclose(f);
        if (returnCode) {
            return false;
        }
    
        *paHandleId = std::stoi(spaHandleId);
        
        return true;
    }