跳转至内容

Advanced Linux Sound Architecture

来自 ArchWiki
(重定向自 Hdajackretask)

The Advanced Linux Sound Architecture (ALSA) provides kernel driven sound card drivers. It replaces the original Open Sound System (OSS)。

Besides the sound device drivers, ALSA also bundles a user space driven library for application developers. They can then use those ALSA drivers for high level API development. This enables direct (kernel) interaction with sound devices through ALSA libraries。

提示 An explanation of ALSA related terminology—interface, card, device (a card is not a device), subdevice, and more—can be found on Wikipedia:Advanced Linux Sound Architecture#Concepts

安装

The ALSA drivers are part of the Linux kernel. The ALSA library (alsa-lib) is usually installed as a dependency. Therefore, manual installation is not necessary。

udev will automatically detect your hardware and select needed drivers at boot time, therefore, your sound should already be working。

However, your sound may be initially muted. If it is, see #Unmuting the channels

固件

The Sound Open Firmware (SOF) (sof-firmware) is usually required for laptops—they tend to utilize Cadence Tensilica Xtensa architecture DSPs, see the list of the supported platforms. In case of the missing firmware the journal will provide messages such as

error: sof firmware file is missing
error: failed to load DSP firmware -2
error: sof_probe_work failed err: -2

For more SOF troubleshooting information, see Overview of Intel hardware platforms

The linux-firmware-cirrus package is needed for laptops with Cirrus Logic smart amplifiers. See also

The linux-firmware-intel package is needed for some Intel audio devices。

The alsa-firmware package contains firmware that may be required for certain sound cards。

See also #Cards and modules and Linux firmware

ALSA 实用程序

Install the alsa-utils package. This contains (among other utilities) the alsamixer(1) and amixer(1) utilities. amixer is a shell command to change audio settings, while alsamixer provides a more intuitive ncurses based interface for audio device configuration。

ALSA 与 systemd

The alsa-utils package comes with systemd unit configuration files alsa-restore.service and alsa-state.service by default。

These are automatically installed and activated during installation (via package provided symlink to sound.target). The options are as follows

  • alsa-restore.service reads /var/lib/alsa/asound.state on boot and writes updated values on shutdown, provided /etc/alsa/state-daemon.conf does not exist. As /etc/alsa/state-daemon.conf is not created without a conscious action of the user, it is the default method。
  • alsa-state.service (Re-)Starts alsactl in daemon mode to continuously keep track of, and persist, volume changes, under the condition that the user has consciously created /etc/alsa/state-daemon.conf

Evidently, both methods are mutually exclusive. You can decide for one of the two approaches depending on your requirements. To edit these units, see systemd#Editing provided units. You can check their status using systemctl.

For further information, see alsactl(1)

用户权限

Local users have permission to play audio and change mixer levels. To allow remote users to use ALSA, you need to add those users to the audio group。

注意 Adding users to the audio group allows direct access to devices. Keep in mind that this allows applications to exclusively reserve output devices. This may break software mixing or fast-user-switching on multi-seat systems. Therefore, adding a user to the audio group is not recommended by default unless you specifically need to

OSS 模拟

OSS emulation is the ability to intercept OSS calls and reroute them through ALSA instead. This emulation layer is useful e.g. for legacy applications which try to open /dev/dsp and write sound data to them directly. Without OSS or the emulation library, /dev/dsp will be missing, and the application will not produce any sound。

If you want OSS applications to work with dmix, install the alsa-oss package as well。

Load the snd_pcm_oss and snd_seq_oss kernel modules. Configure them to load at boot

解除通道静音

By default, ALSA has all channels muted. Those have to be unmuted manually。

使用 amixer 解除静音

Unmuting the sound card's master volume can be done by using amixer

$ amixer sset Master unmute
$ amixer sset Speaker unmute
$ amixer sset Headphone unmute

使用 alsamixer 解除静音

Unmuting the sound card can be done using alsamixer

$ alsamixer

The MM label below a channel indicates that the channel is muted, and OO indicates that it is open。

Scroll to the Master and PCM channels with the Left and Right keys and unmute them by pressing the m key。

Use the Up key to increase the volume and obtain a value of 0 dB gain. The gain can be found in the upper left next to the Item: field。

注意 If gain is set above 0 dB, audible distortion can become present。

解除 5.1/7.1 声道静音

To get full 5.1 or 7.1 surround sound, you will likely need to unmute other channels such as Front, Surround, Center, LFE (subwoofer) and Side. (Those are channel names with Intel HD Audio; they may vary with different hardware)

注意 Please take note that this will not automatically upmix stereo sources (like most music). In order to accomplish that, see #Upmixing

启用麦克风

To enable your microphone, switch to the Capture tab with F4 and enable a channel with Space. See /Troubleshooting#Microphone if microphone does not work。

测试您的更改

Next, test to see if sound works

$ speaker-test -c 2

Change -c to fit your speaker setup. Use -c 8 for 7.1, for instance

$ speaker-test -c 8

If audio is being outputted to the wrong device, try manually specifying it with the argument -D

$ speaker-test -D default:PCH -c 8

-D accepts PCM channel names as values, which can be retrieved by running the following

$ aplay -L | grep :CARD
default:CARD=PCH  # 'default:PCH' is the PCM channel name for -D
sysdefault:CARD=PCH
front:CARD=PCH,DEV=0
surround21:CARD=PCH,DEV=0
surround40:CARD=PCH,DEV=0
surround41:CARD=PCH,DEV=0
surround50:CARD=PCH,DEV=0
surround51:CARD=PCH,DEV=0
surround71:CARD=PCH,DEV=0

附加说明

  • If your system has more than one soundcard, then you can switch between them by pressing F6
  • Some cards need to have digital output muted or disabled in order to hear analog sound and vice versa。
  • Some machines, like the Thinkpad T61, have a Speaker channel which must be unmuted and adjusted as well。
  • Some machines, like the Dell E6400, may also require the Front and Headphone channels to be unmuted and adjusted。
  • If your volume adjustments seem to be lost after you reboot, try running alsamixer as root。

驱动程序配置

For more information, see Advanced Linux Sound Architecture - Driver Configuration guide

To reload ALSA driver configuration you have to reload corresponding modules. Before doing this, all processes using the corresponding ALSA driver—such as PipeWire—must be stopped. To identify processes using sound device files, utilize fuser(1)

# fuser --all --verbose /dev/snd/*

参见

声卡和模块

Run lspci -k -nn -d ::0403 to identify the modules in use for PCI devices。

提示
  • ::0403 here means Audio device subclass of the Multimedia controller PCI device class。
  • Kernel driver in use in lspci output is the loaded module. Kernel modules are capable of handling the device, see lspci(8) § k

Run lsusb --verbose --tree | grep --after-context=1 'Class=Audio' for USB devices。

Run lsmod | grep '^snd' to get a full list of loaded sound modules。

Run cat /proc/asound/cards to get the list of your sound cards with their corresponding indexes (card numbers)。

提示

Run cat /proc/asound/modules to get the card indexes with their corresponding module names。

声卡索引

If you want to change your sound card order (or if your sound card order changes on boot, and you want to make it permanent), reserve the index for the given driver with the slots option of the snd module. See also Kernel module#Setting module options

提示 The name slot comes from the OSS and is equivalent to the ALSA term index

The following sample assumes you want your USB sound card always be the first (i.e. with index 0), no matter when the module is loaded (e.g. the card could be unplugged on boot)

/etc/modprobe.d/alsa-base.conf
options snd slots=snd_usb_audio

When a module name is prepended with an exclamation mark (!), the corresponding index will be given for any modules but that name. For example, reserve the first index (0) for any modules but snd_usb_audio to avoid USB sound cards from getting it

options snd slots=!snd_usb_audio

You can also provide an index of -2 to instruct ALSA to never use a card as the primary one: negative value is interpreted as a bitmask of permissible indexes. The alternative to the previous sample using the index option of the specific module

options snd_usb_audio index=-2

If several sound cards use the same module, and their order is always the same, you can change the order with just index option. The following sample assumes there are two audio cards using the HD Audio module (e.g. an integrated audio card and HDMI output of non-integrated video card), and you want to swap their indexes

options snd_hda_intel index=1,0
提示
  • The sample above reads as "the first sound card which uses snd_hda_intel gives the index 1, and the second one gives the index 0". Which card is first and which one is second is determined by udev
  • ALSA module option often take not just a single value, but an array of values, each one setting the option's value but only for one of the sound cards that a given module is handling. Look for the presence of the array of notion in the output of
$ modinfo --field=parm module_name | column --separator=':' --table --table-columns-limit=2

The slots option can be combined with the index one as long as they do not conflict

options snd slots=,snd_hda_intel,snd_hda_intel,snd_usb_audio,snd_usb_audio,snd_usb_audio
options snd_hda_intel index=2,1
options snd_usb_audio index=3,4,5 vid=0xVID_3,0xVID_4,0xVID_5 pid=0xPID_3,0xPID_4,0xPID_5
提示
  • slots=, means "do not reserve the index zero", so e.g. some USB card—not mentioned in the snd-usb-audio options—plugged in after a boot could be the first.
  • The snd_usb_audio module allows to specify the cards with vid and pid options, so you do not rely on the order from udev

参见

禁用声卡

To disable all cards controlled by a given kernel module, prevent the module from loading using install or module_blacklist approach。

注意 Blacklisting using the blacklist keyword in a modprobe.d configuration file will not work。

To select which card should be disabled, use the enable option of a kernel module. For example, disable the second card operated by a module

/etc/modprobe.d/alsa-base.conf
options module_name enable=1,0

See also /Troubleshooting#Codec probing for an HD Audio card codec disabling。

库配置

The system configuration file is /etc/asound.conf, and the per-user configuration file is ~/.asoundrc

The syntax of library configuration—i.e. whitespace, line continuation, comments, including configuration files, punctuators (separators), assignments, compound assignments, operation modes—is explained in Configuration files

ALSA library configuration is loaded for each instance of the library, so to reload it, all you have to do is restart the programs that are using it。

For more information, see

基本语法

操作模式

There are different operation modes for parsing nodes, the default mode is merge and create. If operation mode is either merge/create or merge, type checking is done. Only same type assignments can be merged, so strings cannot be merged with integers. Trying to define a simple assignment in default operation mode to a compound (and vice versa) will also not work。

Prefixes of operation modes

  • + — merge and create
  • - — merge
  • ? — do not override
  • ! — override
Operation modes
# Merge/create - If a node does not exist, it is created. If it does exist and types match,
# subkeyN is merged into key.
key.subkeyN valueN;

# Merge/create - Equivalent to above
key.+subkeyN valueN;

# Merge - Node key.subkeyN must already exist and must have same data type
key.-subkeyN valueN;

# No override - Ignore new assignment if key.subkeyN node already exists
key.?subkeyN valueN;

# Override - Removes subkeyN and all keys below it, then creates node key.subkeyN
key.!subkeyN valueN;

Using override operation mode, when done correctly, is usually safe; however, one should bear in mind that there might be other necessary keys in a node for proper functioning。

警告 Overriding pcm node itself will most definitely make ALSA unusable, since every plugin definition will be deleted. Therefore, do not use !pcm.key unless you are making a configuration from scratch。

嵌套

Sometimes, it may be useful and even easier to read using nesting in configuration。

Nesting PCM plugins
pcm.azalia {	type hw; card 0	}
pcm.!default {	type plug; slave.pcm "azalia"	}

# is equivalent to

pcm.!default {	type plug; slave.pcm {	type hw; card 0;	}	}

# which is also equivalent to

pcm.!default.type plug;
pcm.default.slave.pcm.type hw;
pcm.default.slave.pcm.card 0;

设置默认声卡

使用“defaults”节点设置默认设备的示例

Assuming that "defaults" node is set in /usr/share/alsa/alsa.conf, where "defaults.pcm.card" and its "ctl" counterpart have assignment values "0" (type integer), user wants to set default pcm and control device to (third) sound card "2" or "SB" for an Azalia sound card。

Defaults node
defaults.ctl.card 2; # Sets default device and control to third card (counting begins with 0).
defaults.pcm.card 2; # This does not change the data type.

defaults.ctl.+card 2; # Equivalent to above.
defaults.pcm.+card 2;

defaults.ctl.-card 2; # Same effect on a default setup, however if defaults node was removed or
defaults.pcm.-card 2; # type has been changed, merge operation mode will result in error.

defaults.pcm.?card 2; # This does nothing, since this assignment already exists.
defaults.ctl.?card 2;

defaults.pcm.!card "SB"; # The override operation mode is necessary here, because of
defaults.ctl.!card "SB"; # different value types.

Using double quotes here automatically sets values data type to string, so in the above example, setting defaults.pcm.!card "2" would result in retaining last default device, in this case card 0. Using double quotes for strings is not mandatory as long as no special characters are used, which ideally should never be the case. This may be irrelevant in other assignments。

注意 From a configuration point of view, those are not equivalent to setting a compound "default" PCM device, since most users specify addressing type in there also, which actually may be the same, but the assignment itself still differs. Also, defaults.pcm.card is referred to multiple times in ALSA configuration files, usually as a fallback assignment, where different environment variables take precedence。

通过 defaults 节点设置默认声卡

Putting the previous example regarding defaults.pcm.card and defaults.pcm.device into practice, assuming we have 2 cards with index 0 and 1 respectively and wish to simply change the default card to index 1, would lead to the following configuration in /etc/asound.conf or the user-specific ~/.asoundrc to change both the playback and the mixer control card。

defaults.pcm.card 1
defaults.ctl.card 1

通过环境变量选择默认 PCM

Probably, it is enough to set ALSA_CARD to the name of the device. First, get the names with aplay -l, then set ALSA_CARD to the name which comes after the colon and before the bracket; e.g. if you have

card 1: HDMI [HDA ATI HDMI], device 3: HDMI 0 [HDMI 0]

then set ALSA_CARD=HDMI

Other variables are also checked in the default global configuration /usr/share/alsa/alsa.conf. By looking there for constructs of the form vars [ ... ], the following table emerges

Variable name Used by
1 ALSA_CARD pcm.default , pcm.hw , pcm.plughw , ctl.sysdefault , ctl.hw , rawmidi.default , rawmidi.hw , hwdep.hw
2 ALSA_CTL_CARD ctl.sysdefault , ctl.hw
3 ALSA_HWDEP_CARD hwdep.default , hwdep.hw
4 ALSA_HWDEP_DEVICE hwdep.default , hwdep.hw
5 ALSA_PCM_CARD pcm.default , pcm.hw , pcm.plughw
6 ALSA_PCM_DEVICE pcm.hw , pcm.plughw
7 ALSA_RAWMIDI_CARD rawmidi.default , rawmidi.hw
8 ALSA_RAWMIDI_DEVICE rawmidi.default , rawmidi.hw

Alternatively, you can override the behavior in your own configuration file, preferably the global one (/etc/asound.conf). Add

pcm.!default {
   type plug
   slave.pcm {
       @func getenv
       vars [ ALSAPCM ]
       default "hw:Audigy2"
   }
}

In this case as well, replace Audigy2 with the name of your device. You can get the names with aplay -l or you can also use PCMs like surround51. But if you need to use the microphone, it is a good idea to select full-duplex PCM as default。

Now, you can select the sound card when starting programs by just changing the environment variable ALSAPCM. It works fine for all programs that do not allow to select the card; for the others, ensure you keep the default card. For example, assuming you wrote a downmix PCM called mix51to20, you can use it with mplayer using the commandline ALSAPCM=mix51to20 mplayer example_6_channel.wav

注意 Pay attention to default addressing type。

直接寻址硬件

警告 This setting leaves the device unavailable to other applications. This method is only recommended if it is a part of a more sophisticated setup ~/.asoundrc or if user deliberately wants to address sound card directly (digital output through IEC958 or dedicated music server for example). This setting without sound server or mixing is not supported by some applications such as Chromium

First, you will have to find out the card and device id that you want to set as the default

$ aplay -l
**** List of PLAYBACK Hardware Devices ****
card 0: Intel [HDA Intel], device 0: CONEXANT Analog [CONEXANT Analog]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 0: Intel [HDA Intel], device 1: Conexant Digital [Conexant Digital]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 1: JamLab [JamLab], device 0: USB Audio [USB Audio]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 2: Audio [Altec Lansing XT1 - USB Audio], device 0: USB Audio [USB Audio]
  Subdevices: 1/1
  Subdevice #0: subdevice #0

For example, the last entry in this list has the card index (card number) 2, card ID strings Audio and the device ID 0. To set this card as the default, you can either use the system-wide file /etc/asound.conf or the user-specific file ~/.asoundrc. You may have to create the file if it does not exist. Then insert the following options with the corresponding card。

pcm.!default {
   type hw
   card Audio #or card 2
   hint {
    show on # for some applications
   }
}

ctl.!default {
   type hw
   card Audio
}

pcm.dmixer {
	type dmix
	ipc_key 2048
	slave {
		pcm "hw:Audio" #or "hw:2"
	}
}

pcm.dsnooper {
	type dsnoop
	ipc_key 2048
	slave {
		pcm "hw:Audio"
	}
}

It is recommended to use sound card ID strings instead of number references to overcome the boot order problem。

注意 This method could be problematic if your system has several cards of the same ID string (with _1, _2, … suffixes appended). For more information, see Identify two identical audio devices

pcm.dmixer and pcm.dsnooper are spares for applications which does not support without mixing

本文或本章节的准确性存在争议。

原因: General method to select ALSA device should be introduced such as environment value. (Discuss in Talk:Advanced Linux Sound Architecture)

For example, chromium -alsa-output-device=pcm.dmixer -alsa-input-device=pcm.dsnooper enables mixing for Chromium tempolary。

The pcm options affect which card and device will be used for audio playback while the ctl option affects which card is used by control utilities like alsamixer

The changes should take effect as soon as you (re-)start an application (e.g. MPlayer). You can also test with a command like aplay

$ aplay -D default:PCH your_favourite_sound.wav

If you receive an error regarding your asound configuration, check the upstream documentation for possible changes to the configuration file format。

插件

Install the alsa-plugins package if you need to enable #Upmixing, #Downmixing, #High quality resampling and other advanced features。

For more information, see PCM (digital audio) plugins

软件混音

Mixing enables multiple applications to output sound at the same time. Most discrete sound cards support hardware mixing, which is enabled by default if available. Integrated motherboard sound cards (such as Intel HD Audio), usually do not support hardware mixing. On such cards, software mixing is done by an ALSA plugin called dmix. This feature is enabled automatically if hardware mixing is unavailable。

注意 Software mixing is enabled by default for sound cards which do not support hardware mixing. dmix is not enabled by default for digital output (S/PDIF) and will require the configuration snippet below。

To manually enable dmix, add the following to your ALSA configuration file

/etc/asound.conf
pcm.dsp {
    type plug
    slave.pcm "dmix"
}

上混

In order for stereo sources like music to be able to saturate a 5.1 or 7.1 sound system, you need to use upmixing. In darker days, this used to be tricky and error prone, but nowadays, plugins exist to easily take care of this task. We will use the upmix plugin, included in the alsa-plugins package。

Then add the following to your ALSA configuration file of choice (either /etc/asound.conf or ~/.asoundrc)

pcm.upmix71 {
   type upmix
   slave.pcm "surround71"
   delay 15
   channels 8
}

You can easily change this example for 7.1 upmixing to 5.1 or 4.0。

The following example adds a new PCM channel that you can use for upmixing. If you want all sound sources to go through this channel, add it as a default below the previous definition like so

pcm.!default "plug:upmix71"

The plugin automatically allows multiple sources to play through it without problems so setting is as a default is actually a safe choice. If this is not working, you have to setup your own dmixer for the upmixing PCM like this

pcm.dmix6 {
   type asym
   playback.pcm {
       type dmix
       ipc_key 567829
       slave {
           pcm "hw:0,0"
           channels 6
       }
   }
}

and use "dmix6" instead of "surround71". If you experience skipping or distorted sound, consider increasing the buffer_size (to 32768, for example) or use a high quality resampler

下混

If you want to downmix sources to stereo because you, for instance, want to watch a movie with 5.1 sound on a stereo system, use the vdownmix plugin, included in the alsa-plugins package。

Again, in your configuration file, add this

pcm.!surround51 {
   type vdownmix
   slave.pcm "default"
}
pcm.!surround40 {
   type vdownmix
   slave.pcm "default"
}
注意 This might not be enough to make downmixing working; see [1]. So, you might also need to add pcm.!default "plug:surround51" or pcm.!default "plug:surround40". Only one vdownmix plug can be used; if you have 7.1 channels, you will need to use surround71 instead the configuration above. A good example, which includes a configuration that makes both vdownmix and dmix working, can be found in [2].

多段均衡器

Multiband EQ (mbeq)

is a fairly typical multiband graphical equalizer. It is implemented using a fast Fourier transform (FFT), so it takes quite a lot of CPU power, but should have less phase effects than an equivalent filter implementation. If the input signal is at too low sample rate, then the top bands will be ignored—the highest useful band will always be a high shelf。

mbeq is part of Steve Harris' LADSPA plugin suite

如果您还没有安装,请安装 alsa-pluginsladspaswh-plugins 软件包。

如果您还没有创建 `~/.asoundrc` 或 `/etc/asound.conf` 文件,请创建一个,然后插入以下内容:

/etc/asound.conf
pcm.eq {
    type ladspa

    # The output from the EQ can either go direct to a hardware device
    # (if you have a hardware mixer, e.g. SBLive/Audigy) or it can go
    # to the software mixer shown here.
    #slave.pcm "plughw:0,0"
    slave.pcm "plug:dmix"

    # Sometimes, you may need to specify the path to the plugins,
    # especially if you have just installed them.  Once you have logged
    # out/restarted, this should not be necessary, but if you get errors
    # about being unable to find plugins, try uncommenting this.
    #path "/usr/lib/ladspa"

    plugins [
    {
        label mbeq
        id 1197
        input {
            # The following setting is just an example, edit to your own taste:
            # bands:
            #   50 Hz,  100 Hz,  156 Hz,  220 Hz,  311 Hz,   440 Hz,   622 Hz,  880 Hz,
            # 1250 Hz, 1750 Hz, 2500 Hz, 3500 Hz, 5000 Hz, 10000 Hz, 20000 Hz
            controls [ -5 -5 -5 -5 -5 -10 -20 -15 -10 -10 -10 -10 -10 -3 -2 ]
            }
        }
    ]
}

# Redirect the default device to go via the EQ - you may want to do
# this last, once you are sure everything is working.  Otherwise, all
# your audio programs will break/crash if something has gone wrong.
pcm.!default {
    type plug
    slave.pcm "eq"
}

# Redirect the OSS emulation through the EQ too (when programs are running through "aoss")
pcm.dsp0 {
    type plug
    slave.pcm "eq"
}

ALSAEqual

系统级

安装 alsaequalAUR 软件包。

安装软件包后,将以下内容添加到您的 ALSA 配置文件中:

/etc/asound.conf
ctl.equal {
    type equal;
}

pcm.plugequal {
    type equal;
    # Normally, the equalizer feeds into dmix so that audio
    # from multiple applications can be played simultaneously:
    slave.pcm "plug:dmix";
    # If you want to feed directly into a device, specify it instead of dmix:
    #slave.pcm "plughw:0,0";
}

# Configuring pcm.!default will make the equalizer your default sink
pcm.!default {
# If you do not want the equalizer to be your default,
# give it a different name, like pcm.equal commented below
# Then you can choose it as the output device by addressing
# it in individual apps, for example mpg123 -a equal 06.Back_In_Black.mp3
# pcm.equal {
    type plug;
    slave.pcm plugequal;
}

要更改均衡器设置,请运行:

$ alsamixer -D equal

请注意,均衡器配置因用户而异(除非另有说明)。它保存在 `~/.alsaequal.bin` 中。因此,如果您想将 ALSAEqual 与在不同用户下运行的 mpd 或其他软件一起使用,您可以使用以下方法进行配置:

$ su mpd -c 'alsamixer -D equal'

或者,例如,您可以为他们的主目录创建一个指向您的 `.alsaequal.bin` 的符号链接。

仅特定输出

如果您希望仅将均衡器应用于特定输出设备(例如连接到 S/PDIF 输出的扬声器,而不是连接到耳机插孔的耳机),但同时希望能够从多个应用程序输出并同时输出到两个输出设备,您需要创建两个 `dmix` 设备,这些设备直接馈入各自的设备(`slave.pcm`)。以下配置适用于立体声输出并保持常规立体声输入,仅将均衡器应用于 S/PDIF 输出。

/etc/asound.conf
#
#  (capture.pcm)  <-- dnsoop
#        |
# !default                               --> dmixa
#        |                               |
#  (playback.pcm) --> stereo2quad ==> quad
#                                        |
#                                        --> softvol --> plugequal --> dmixd
#

# dmix for analog output
pcm.dmixa {
  type dmix
  ipc_key 1024
  ipc_perm 0666
  slave.pcm "hw:PCH,0"
  slave {
    period_time 0
    period_size 1024
    buffer_size 4096
    channels 2
  }
  bindings {
    0 0
    1 1
  }
}

# dmix for digital output
pcm.dmixd {
  type dmix
  ipc_key 2048
  ipc_perm 0666
  slave.pcm "hw:PCH,1"
  slave {
    period_time 0
    period_size 1024
    buffer_size 4096
    channels 2
  }
  bindings {
    0 0
    1 1
  }
}

# equalizer with controls
pcm.plugequal {
  type equal
  slave {
    pcm "plug:dmixd"
  }
}
ctl.equal {
 type equal
}

# Volume control for S/PDIF
pcm.softvol {
    type softvol
    slave.pcm "plug:plugequal"
    control {
        name "S/PDIF"
    }
}

# multi:
# "a" (analog)  -> dmix,
# "d" (digital) -> softvol -> plugequal -> dmix
pcm.quad {
    type multi
    slaves {
      a.pcm "dmixa"
      a.channels 2
      d.pcm "plug:softvol" # detour via softvol and equalizer
      d.channels 2
    }
    bindings {
      0 { slave a; channel 0; }
      1 { slave a; channel 1; }
      2 { slave d; channel 0; }
      3 { slave d; channel 1; }
    }
}

# stereo to quad
pcm.stereo2quad {
  type route
  slave.pcm "quad"
  ttable [
    [ 1 0 1 0 ]
    [ 0 1 0 1 ]
  ]
}

# playback to stereo to quad, capture as usual
pcm.!default {
  type asym
  playback.pcm "plug:stereo2quad"
  capture.pcm "plug:dnsoop"
}

管理状态

安装 alsaequal-mgrAUR 软件包。

使用以下命令按常规配置均衡器:

$ alsamixer -D equal

当您对某个状态满意后,可以为其命名(本例中为 foo)并保存:

$ alsaequal-mgr save foo

之后,可以通过以下方式恢复名为 "foo" 的状态:

$ alsaequal-mgr load foo

但是,这只会恢复 `~/.alsaequal.bin`。然后您需要通过 `alsamixer -D equal` 更新均衡器。

因此,您可以为游戏、电影、音乐类型、VoIP 应用等创建不同的均衡器状态,并在需要时重新加载它们。

有关更多选项,请参阅 项目页面 和帮助消息。

技巧与提示

高质量重采样

当启用 #软件混音 时,ALSA 会被强制将所有内容重采样到相同的频率(默认情况下为 48 kHz,如果支持)。默认情况下,它会 尝试使用 `speexrate` 转换器来执行此操作,如果不可用,则回退到低质量的线性插值。因此,如果您因为重采样质量差而导致声音质量不佳,只需安装 alsa-plugins 软件包即可解决问题。

为了获得更高质量的重采样,您可以将默认采样率转换器更改为 `speexrate_medium` 或 `speexrate_best`。两者表现都足够好,以至于在实践中选择哪一个并不重要,因此使用最佳转换器通常不值得额外的 CPU 周期。

要更改默认转换器,请将以下内容放入您的 `~/.asoundrc` 或 `/etc/asound.conf`:

defaults.pcm.rate_converter "speexrate_medium"
  • 也可以使用 libsamplerate 转换器,它们的速度大约是 `speexrate` 转换器的一半,但质量并没有高出多少。
  • 也可以使用 使用 libavresample 的速率转换器插件,它使用 FFmpeg。`lavcrate_high` 和 `lavcrate_higher` 分别等同于 Kodi 的低和中等质量重采样器。
  • 一些应用程序(如 MPlayer 及其分支)默认会自行进行重采样,因为某些 ALSA 驱动在启用重采样时存在延迟报告不正确的问题(从而导致音视频不同步)。因此,除非您将它们配置为使用 ALSA 重采样,否则更改此设置将不会产生任何效果。

禁用启动时的自动静音

可以使用 `amixer` 在启动时配置“自动静音模式”。例如,要禁用它:

# amixer -c 0 sset "Auto-Mute Mode" Disabled

或者,可以通过 `alsamixer` 使用基于 ncurses 的界面。为了保存任何修改,请使用:

# alsactl store

或者

# alsactl daemon

另请参阅 #ALSA 和 systemd

USB 声卡热插拔

请参阅 为 ALSA 编写 Udev 规则

同时输出

您可能希望通过通过迷你插孔连接的外部扬声器和内部扬声器同时播放音乐。这可以通过使用 `alsamixer` 或 `amixer` 来取消静音 **自动静音** 项来完成:

$ amixer sset "Auto-Mute" unmute

然后取消静音其他必需的项,例如 **耳机**、**扬声器**、**低音扬声器**...

注意 如果您的耳机插孔(迷你插孔)出现噼啪声,请参阅 /Troubleshooting#Crackling sound through mini-jack (headphones connector)

键盘音量控制

以下命令映射到您的音量键:`XF86AudioRaiseVolume`、`XF86AudioLowerVolume`、`XF86AudioMute`。

增大音量

amixer set Master 5%+

减小音量

amixer set Master 5%-

切换静音/取消静音音量

amixer set Master toggle

使用 snd_aloop 的虚拟声卡

您可能需要一个 jack 替代方案来创建一个虚拟录音或播放设备,以便混音不同的源,使用 `snd_aloop` 模块:

modprobe snd_aloop

使用以下命令列出您的新虚拟设备:

aplay -l

现在您可以使用 ffmpeg,例如:

ffmpeg -f alsa -i hw:1,1,0 -f alsa -i hw:1,1,1 -filter_complex amerge output.mp3

在 `hw:R,W,N` 短语中,R 是您的虚拟声卡设备编号。W 应设置为 1 表示录音设备,或 0 表示播放设备。N 是您的子设备。您可以使用所有可用的虚拟设备,并通过 mplayer 等应用程序进行播放/停止。

mplayer -ao alsa:device=hw=1,0,0 fileA
mplayer -ao alsa:device=hw=1,0,1 fileB

您还可以使用此方法执行其他操作,例如使用 Festival 通过类似以下脚本的脚本生成语音到录音流中:

#!/bin/sh
echo "$1" | iconv -f utf-8 -t iso-8859-1 | text2wave  > "_tmp_.wav"
mplayer -ao alsa:device=hw=2,0,0 "_tmp.wav"
rm "_tmp.wav"

重新配置输入/输出端口

软件包 `alsa-tools` 包含 `hdajackretask` 工具,该工具(在 Intel HDA 声卡上)可用于重新配置声卡的输入/输出端口;例如,将麦克风插孔变成耳机插孔。

apulse

apulseAUR 提供了 PulseAudio API 的一个 替代性部分实现。它允许您将 ALSA 用于仅支持 PulseAudio 的应用程序。用法很简单:

$ apulse application

参见