首页 > 解决方案 > Pulseaudio C API:创建一个空接收器

问题描述

我正在尝试创建 2 个简单的程序,它们基本上是pulseaudio 文档中的 parec-simple 和 pacat-simple 示例。唯一的区别是我想创建一个空接收器,相当于

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

(请参见此处的示例)然后我将使用它来代替两端的默认设备 - 播放和录制。

我的问题是:如何使用 pulseaudio 的 C API 创建这个空接收器?从我所见,pulse/simple.h 不包含任何函数定义来执行此操作,所以我想我必须使用 libpulse。

标签: cpulseaudio

解决方案


我找不到它的pulseaudio API,所以我直接使用pactl 接口。

对于任何感兴趣的人,这里有一个对我有用的示例代码。我只是使用popen执行 pactl 命令来创建一个(空)接收器:

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;
}

推荐阅读