如何使用alsa库API与耳机和扬声器配合使用?

时间:2019-04-25 02:42:40

标签: c audio alsa libalsa amixer

我想使用c程序为扬声器和耳机实现(静音/取消静音和调高/调低音量)。使用此链接https://askubuntu.com/questions/371970/how-to-switch-between-headphones-and-speakers-manually-from-command-line中所示的amixer命令行实用程序可以正常工作,同样,我需要使用C程序。

所以我尝试了以下不同的方法。 我看过这个例子来控制Master的音量 Set ALSA master volume from C code

以及静音/取消静音 Linux ALSA/Sound-API Questions - How do you mute?

两种解决方案都非常适合主配置。 但是在我的情况下,我想为扬声器和耳机实现相同的功能。因此,如果我用amixer命令将 selem_name 替换为Speaker或Headphone + L0而不是“ Master”,则会引发错误。 / p>

在这里,我需要静音/取消静音“扬声器”或“耳机”。

如果在下面的代码中使用* selem_name =“ Speaker”或“ Headphone”,则会引发如下所示的错误:

给定的selem_name无效吗? 如果是这样,如何列出扬声器和耳机的有效selem_name? 我使用了它从amixer命令行实用工具中得出的结果。

我必须为扬声器和耳机使用什么API?

Errorr eturn by test.c program:

alsa: simple.c:346: snd_mixer_selem_has_playback_switch: Assertion 
`elem' failed.
Aborted

//test.c

#include<stdio.h>
#include<alsa/asoundlib.h>

void SetAlsaSpeakerMute()
{
    snd_mixer_t *handle;
    snd_mixer_selem_id_t *sid;
    const char *card = "default";

    const char *selem_name = "Speaker";

    snd_mixer_open(&handle, 0);
    snd_mixer_attach(handle, card);
    snd_mixer_selem_register(handle, NULL, NULL);
    snd_mixer_load(handle);

    snd_mixer_selem_id_alloca(&sid);
    snd_mixer_selem_id_set_index(sid, 0);
    snd_mixer_selem_id_set_name(sid, selem_name);
    snd_mixer_elem_t* elem = snd_mixer_find_selem(handle, sid);

    if (snd_mixer_selem_has_playback_switch(elem)) {
        snd_mixer_selem_set_playback_switch_all(elem, 0);
    }

    snd_mixer_close(handle);
}

int main()
{
    SetAlsaSpeakerMute();
    return 0;
}
//For const char *selem_name = "Master" this program works fine.
//This can mute Mixer of default sound card

void SetAlsaMasterMute()
{
    snd_mixer_t *handle;
    snd_mixer_selem_id_t *sid;
    const char *card = "default";
    const char *selem_name = "Master";

    snd_mixer_open(&handle, 0);
    snd_mixer_attach(handle, card);
    snd_mixer_selem_register(handle, NULL, NULL);
    snd_mixer_load(handle);

    snd_mixer_selem_id_alloca(&sid);
    snd_mixer_selem_id_set_index(sid, 0);
    snd_mixer_selem_id_set_name(sid, selem_name);
    snd_mixer_elem_t* elem = snd_mixer_find_selem(handle, sid);

    if (snd_mixer_selem_has_playback_switch(elem)) {
        snd_mixer_selem_set_playback_switch_all(elem, 0);
    }

    snd_mixer_close(handle);
}

是否有解决方案来静音/取消静音特定设备(扬声器和耳机)?所有帮助表示感谢。

1 个答案:

答案 0 :(得分:1)

同样,您使用的控件名称的elem变量似乎为NULL。

您应检查混音器连接的控件ID(名称,索引,接口)和控件设备。 “默认”设备名称通常重定向到脉冲音频(仅主/ PCM控件)。如果将'-c 0'用于混音器,则正确的设备名称为'hw:0'(const char * card =“ hw:0”;)。

相关问题