ALSA

From Gentoo Wiki
Jump to:navigation Jump to:search
This page is a translated version of the page ALSA and the translation is 48% complete.
Outdated translations are marked like this.
Other languages:


这篇文章介绍了使用 ALSA(Advanced Linux Sound Architecture) 设置声卡的方法。

安装

硬件检测

重要
在安装 ALSA 过程中,经常发现声卡的内核驱动模块未在系统上正确安装。要检查系统是否有工作的声卡驱动模块,可以运行 lsmod。如果没有带有 snd_ 前缀的模块,请考虑为系统的特定声卡正确安装内核驱动模块。更详细的指南可以在 Kernel Modules 页面找到。

要选择正确的驱动程序,首先要检测使用的音频控制器。使用 lspci 来完成这个任务:

user $lspci | grep -i audio

确定控制器名称后,可以在 ALSA 声卡矩阵 中找到所需的驱动程序。

内核

激活以下内核选项:

内核
Device Drivers --->
    <*> Sound card support
        <*> Advanced Linux Sound Architecture --->
            [*] PCI sound devices  --->
                Select the driver for your audio controller.
                HD-Audio  --->
                   Select a codec or enable all and let the generic parse choose the right one:
                   [*] Build Realtek HD-audio codec support
                   [*] ...
                   [*] Build Silicon Labs 3054 HD-modem codec support
                   [*] Enable generic HD-audio codec parser
            [*] USB sound devices  --->
                Must have as some cards are presented as USB devices.
                [*] USB Audio/MIDI driver
General setup --->
    [*] System V IPC

lsmod 命令能给你提供帮助。

如果系统有超过 8 个声音输出(GPU 上的每个 HDMI 输出将计为一个),则需要增加最大声卡数量:

内核
Device Drivers --->
    <*> Sound card support
        <*> Advanced Linux Sound Architecture --->
            [*] Dynamic device file minor numbers
            (32) Max number of sound cards

软件

Portage 知道全局 USE 标记 alsa 用于在其他包中启用对 ALSA 的支持。启用此 USE 标记将自动引入 media-libs/alsa-lib(默认在 x86amd64 桌面特定配置文件中):

root #euse -E alsa

euse 命令包含于 app-portage/gentoolkit

USE flags for media-libs/alsa-lib Advanced Linux Sound Architecture Library

alisp Enable support for ALISP (ALSA LISP) interpreter for advanced features.
debug Enable extra debug codepaths, like asserts and extra output. If you want to get meaningful backtraces see https://wiki.gentoo.org/wiki/Project:Quality_Assurance/Backtraces
doc Add extra documentation (API, Javadoc, etc). It is recommended to enable per package instead of globally
python Add optional support/bindings for the Python language

配置以后,务必要更新系统来使得某些配置生效。

root #emerge --ask --changed-use --deep @world

设置好必要的 USE 标志后,即可安装 ALSA 软件包。使用如下的 emerge 命令进行安装:

root #emerge --ask media-libs/alsa-lib

media-sound/alsa-utils 包提供了一些用于对声音系统进行故障排除和测试的工具。如果尚未安装软件包,最好将其合并到系统中:

root #emerge --ask media-sound/alsa-utils

配置

文件

  • /etc/asound.conf - 全局(整个系统)配置文件。
  • ~/.asoundrc - 本地(每个用户)配置文件。

~/.asoundrc

可以选择使用此文件,以便在每个用户的基础上选择性覆盖 ALSA 默认值。如果系统具有特殊硬件,那么声卡 0 和设备 0(默认值)可能无法工作。

最简单的更改之一是声卡和设备。对我来说,HDMI 是来自连接到板载 Realtek ALC88* 音频设备上的 Nvidia 声卡。

文件 ~/.asoundrc
defaults.pcm.!card 1
defaults.pcm.!device 7

如果你无法找到分配给你打算使用的声卡的设备号,请不要惊慌 —— 卡号在内部是一个你能够使用的名称。如果你的声卡像这样列出...

user $aplay -L
front:CARD=Generic,DEV=0
HD-Audio Generic, ALC282 Analog
Front speakers

... 那么这意味着 ~/.asoundrc 文件应该是这样的:

文件 ~/.asoundrc
defaults.pcm.!card Generic
defaults.pcm.!device 0
defaults.ctl.!card Generic
警告
这些设置会禁用所有软件混音。要将所有输出设置为 96kHz,请将 defaults.pcm.dmix.rate 96000 添加到 ~/.asoundrc 文件中。

当使用多个声卡时,设备编号可以跨引导重新排序,因此使用名称是有利的。

如果正确名称不清楚,可以通过以下方式轻松获取有效名称列表:

user $cat /sys/class/sound/card*/id

以下是具有多个声卡的开发人员系统的输出:

user $cat /sys/class/sound/card*/id
Q1U
HDMI
PCH
C930e

在这里,我们将 Q1U 麦克风设为 Q1U,将内置 HDMI 设为 HDMI,将模拟音频插孔设为 PCH,将网络摄像头的内置麦克风设为 C930e。其中任何一个都是该声卡的有效名称。

警告
在使用多个声卡时指定编号而不是名称可能会导致设备在启动时重新排序,这将阻止声音正常工作,直到配置文件使用新编号编辑。

S/PDIF 或 HDMI .asoundrc

背景

大多数声卡允许使用 S/PDIF 数字同轴或光缆将音频传送到外部接收器或 DAC。这样做可以保留音质和压缩的 Dolby/DTS 编码素材。未压缩的 Dolby/DTS 或蓝光素材,需要 HDMI 连接。更常见的单声道或模拟立体声电缆无法传输 Dolby/DTS 信号。

你可能会发现默认安装的 ALSA 的 S/PDIF 或 HDMI 连接无需.asoundrc 文件更改即可工作。而只有某些应用程序,例如 Web 浏览器 Flash 插件会无法播放声音。因此,大多数 S/PDIF 和 HDMI 连接通常需要以下 .asoundrc。此外,任何打开的媒体应用程序都需要重新启动,.asoundrc 文件才能生效。 (即带有 Flash 插件的 Web 浏览器)

首选连接与媒体类型

基本模拟

基本模拟(即 RCA)连接 —— 基本用户。音质取决于声卡 DAC。寻找具有高 SNR 分贝级别的声卡。

S/PDIF

S/PDIF 为包含 Dobly/DTS 压缩信号的音乐、视频和 DVD 质量电影提供优质音频。近来,大多数声卡和主板都提供某种 S/PDIF 端口。现今,在主板上看到 S/PDIF Toslink 端口更为常见。许多电脑游戏提供压缩的 Dolby/DTS 信号。

S/PDIF 数字同轴

S/PDIF 数字同轴可能存在电压串扰问题,但却更为常见,因为它只需要一个简单的迷你插孔或 RCA 同轴电缆。

S/PDIF 光纤 (Toslink)

S/PDIF 光纤 (Toslink) 电缆完全避免了电缆之间可能的电气串扰或干扰,因为它是光纤,但如果电缆弯曲太多,则容易受到信号衰减的影响。你会发现发烧友倾向于使用 Optical/Toslink。

HDMI

HDMI (High-Definition Multimedia Interface) cable can carry compressed Dolby/DTS and uncompressed (i.e. Blu-ray) Dolby/DTS signals. The audio market has favored this connection, but still preserves S/PDIF connections. One concern being, HDMI cables are copper wire, still susceptible to electrical cross talk or interference, similar to S/PDIF Digital Coaxial connections.

HDMI optical cables are produced, but they are generally too expensive for the consumer market. If audiophiles have S/PDIF Optical ports, they will use the S/PDIF connections for other media such as music and DVD movies, while only using HDMI when needed for processing uncompressed Dolby/DTS encoded material such as Blu-ray media. Again, the basic user will likely just use HDMI, avoiding the fuss of changing configuration files.

配置

找到数字输出设备:

user $aplay --list-devices

调整以下文件以使用声卡/设备号。

{{FileBox|filename=~/.asoundrc|1= pcm.!spdif {

    type hw
    card 0
    device 1

}

附注
The above will not allow sound to be played from more than one sound application, or more than two sounds played at once through one sound card. In order to perform this task, the sounds are remixed with a slight degradation with sound quality. Most people listening to music, prefer not to allow this due to interruptions and decreased sound quality. However, for those that desire this, the above commented section of code will achieve this.
附注
When playing sound files using aplay, the beginning of the playback will be clipped because the digital S/PDIF or HDMI connection is not held open and needs to be started each time a sound file is played. Notice Microsoft Windows both, holds open the receiver or DAC and remixes media on playback.

A/52, AC3, Dolby, DTS

Sound cards providing S/PDIF output can pass through lossy compressed multichannel audio. To my ears, the high bit rate compressed media has little loss in comparison to two channel CD or DVD audio. I surmise this is because we now have multichannels feeding multiple speakers. Hence, the more hardware, the equivelant or better sounding?

If a sound card states it has S/PDIF, it will likely pass through Dolby or DTS even though it does not specifically show a Dolby or DTS icon or listed within its features. This is because, when they do list Dolby or DTS, it is because they're providing software for upmixing, or providing the decoded signal through analog output.

HDMI will pass through uncompressed multichannel audio, but a video feed is interleaved as required by the HDMI specification. In comparison to DVD video and audio, I see and hear very little quality difference, if any! About the only thing I noticed between S/PDIF Toslink and HDMI, HDMI seems to amplify the signal by a few watts or 5db. (I conclude this is because of the higher bit rate?)

因此,即使在今天,S/PDIF 仍然非常流行。

附注
A S/PDIF or HDMI connection is required for passing through advanced encodings. Analog connections (RCA and minijacks) do not support any advanced encoding.

Decoding or encoding to Dolby or DTS requires a license. If you have already purchased a sound card with this multichannel support, then you likely already have a license. See this article for more information.

ALSA media-plugins/alsa-plugins package requires recompilation to include the ffmpeg USE Flag with the A/52 (pcm.a52encode) plugin.

root #USE="ffmpeg" emerge -q media-plugins/alsa-plugins

解码或播放

重新编译 mplayer 或其他喜欢的播放器软件以包含 ALSA 库。

root #USE="a52 dts" emerge -q media-video/mplayer

Add the multichannel codecs to mplayer.conf, so media attempting to be played has first been provided the option of hardware passthrough rather then down mixing.

文件 /etc/mplayer/mplayer.conf
ac=hwac3,hwdts,hwmpa,spdifac3,spdifeac3,spdifaac,spdifdts,spdifmpa,spdifthd,dts,ffaac,

你现在应该能够通过 S/PDIF 将几乎所有 Dolby 或 DTS 信号传递(并享受)到接收器。

编码为 A/52

Upmix two channel audio to a A/52 multi-channel audio stream

To simulate A/52 encoded audio from normal one or two channel audio streams or files, ALSA can upmix using its A/52 plugin. (A/52 is also known as AC-3 or Dolby Digital encoding.)

A/52 upmixing preferred when playing computer games or watching video without Dolby/DTS encoded material, such as older Movies. Many sound card manufacturers provide their applications with a feature for software upmixing to Dolby Digital, and recommend enabling this upmixing when listening to such media, except for Music.

Upmixing to A/52 is frowned upon by audiophiles. As such, it is a user's preference to upmix all the sounds to A/52 before sending the stream to the consumer stereo receiver or DAC. Matter of fact, audiophiles prefer simple stereo, and further state stereo is still better quality than Dolby/DTS material or other audio encoded with gimmicks. Also, the consumer stereo or DAC likely possibly includes a feature for upmixing audio into five channel audio.

{{FileBox|filename=~/.asoundrc| pcm.!default {

   type plug:surroundaudio

}

user $speaker-test -Dsurroundaudio -c 6
将 PCM 5.1 24 位音频编码为 A/52 16 位音频流(用于通过 S/PDIF 进行流式传输)

Also known as, encoding PCM 5.1 audio stream into a compressed Dolby Digital stream for playing over S/PDIF. No real need to use this if you're using HDMI, as HDMI can handle the bandwidth of a PCM 5.1 audio stream. S/PDIF Toslink has also supposedly been upgrade to do so also, but most hardware has yet to be upgraded to the new specifications, and some doubt it will ever happen.

For some reason, the previous .asoundrc section previously mentioned doesn't work with PCM 5.1 streams. Another issue I run into with 24 bit PCM 5.1 audio streams, they require downmixing from S24_LE to S16_LE bit format. Reason being, 24 bit is a common format for most media, however receivers can sometimes only decode 16 or 32 bit audio. Also, the S/PDIF can only handle 16 bit audio when encoding to multi-channel formats such as A/52, for the time being until S/PDIF TosLink hardware specifications are upgraded.

The following .asoundrc excerpt will encode a PCM 5.1 24 bit stream into a 16 bit A/52 stream, for streaming over S/PDIF.

文件 ~/.asoundrc
#####
# Description: This will make it possible to use a52 with PulseAudio out of 
#          the box. It may be useful for other use cases. Just include 
#          this in the ~/.asoundrc file.
&lt;/div&gt;

{{Cmd|aplay -D pcm.a52 /home/me/Music/Led_Zeppelin/Celegration_Day/PCM51-24bit/*.wav}}

=== 为 2 个或更多设备克隆音频 ===

&lt;div lang="en" dir="ltr" class="mw-content-ltr"&gt;
Sometimes you need to clone audio (example using 2 cloned screens with different inputs (first screen HDMI and second screen DVI + Analog audio)).
This is a simple script that you can use as global or local configuration for clone 2 (or more) channels.
You must adjust to your system the lines below commented lines.
More information of the author of the script and forum discussion [https://forums.gentoo.org/viewtopic-t-902670-start-0.html here.]
&lt;/div&gt;

&lt;div class="mw-translate-fuzzy"&gt;
{{FileBox|filename=/etc/asound.conf|&lt;nowiki&gt;
ctl.!default {
   type hw
   #set Your default card
   card 0
}
&lt;/div&gt;

&lt;div lang="en" dir="ltr" class="mw-content-ltr"&gt;
=== JACK audio connection kit ===
&lt;/div&gt;

&lt;div lang="en" dir="ltr" class="mw-content-ltr"&gt;
It is possible to interconnect JACK and ALSA. At that time of writing, the best solution and it look like to be the final one, is via the snd-loopback module and the jack ALSA plugin. For that, see {{See also|JACK#ALSA}} - Bridging ALSA and JACK together. See {{See also|JACK}}.
&lt;/div&gt;

&lt;div lang="en" dir="ltr" class="mw-content-ltr"&gt;
What follow is a general introduction to JACK, some parts of it can be outdated.
&lt;/div&gt;

&lt;div lang="en" dir="ltr" class="mw-content-ltr"&gt;
Jack provides an additional layer, to the already low latency ALSA drivers and applications, and further it guarantees a constant sound latency and synchronous operation of all its clients. Jack can only use one sound card at a time, and will provide separated outputs and inputs for each audio channel of the sound card. Jack further provides the ability to view, manipulate or pipe audio streams, both hardware and software streams, in a similar manner we use cables to interface different audio equipment. As example, [http://jamin.sourceforge.net JAMin] can intercept an audio stream before exporting the stream to another audio application and/or through analog or S/PDIF outputs.  The Jack user owned daemon, is usually started using [https://qjackctl.sourceforge.io/ qjackctl]. The qjackctl utility provides many other functions including audio stream connections.
&lt;/div&gt;

&lt;div lang="en" dir="ltr" class="mw-content-ltr"&gt;
What Jack does not do, is handle A/52 encoded (AC-3 or Dolby/DTS) material on input; it is just a sound server that deal with separated channels of audio streams. And it has the capability to connect simultaneously and synchronously any output stream on any input, and any input to any output stream, that on any hardware and software audio component, and with a constant latency. This make JACK an outstanding tool for audio production and creation. The [https://sonosaurus.com/ac3jack/ ac3jack] tool can be used for encoding multiple separated audio channels to AC-3 streams.
&lt;/div&gt;

&lt;div lang="en" dir="ltr" class="mw-content-ltr"&gt;
When playing an A/52 encoded media, the player will request as many outputs from JACK than audio channels in the media. This will fail if your sound card doesn't have the requested amount of audio outputs, but will be fine otherwise. As example, you can use {{c|mplayer}} as usual, and configure it to output a 5.1 stream on a 7.1 output configuration, or a 7.1 stream on a 2 channels stereo output.
&lt;/div&gt;

&lt;div lang="en" dir="ltr" class="mw-content-ltr"&gt;
One solution is to configure your kernel and ALSA according to Jack installation instructions for providing low latency audio. Since ALSA is said to be already very efficient and low latency, providing very good quality playback with no additional mixing when stated within its {{Path|.asoundrc}} file, unlike MS Windows, Jack probably isn't needed for most. The main audience of JACK is audio producers and musicians (in studio, live performances, DJ, ...). The proaudio-gentoo overlay is available with eselect-repository.
&lt;/div&gt;

&lt;div lang="en" dir="ltr" class="mw-content-ltr"&gt;
For an older solution using the zita-ajbridge, see [https://web.archive.org/web/20220314041206/https://proaudio.tuxfamily.org/wiki/index.php?title=DAW_Digital_Audio_Workstation#Using_an_ALSA_Loopback_device_and_zita-ajbridge Using an ALSA Loopback device and zita-ajbridge] on the ProAudio Gentoo overlay wiki.
&lt;/div&gt;

&lt;div lang="en" dir="ltr" class="mw-content-ltr"&gt;
Using zita-ajbridge, it is also possible to add additional real sound cards into JACK. (Example needed)
&lt;/div&gt;

&lt;div lang="en" dir="ltr" class="mw-content-ltr"&gt;
Those who want to try JACK must know one thing: You will need a realtime kernel and rt operations only if you want to make a Digital Audio Workstation (DAW) with your computer, which necessitate something pulseaudio is not able to achieve: constant sound latency as low or lower than 20 msec (pulseaudio is not able to provide constant sound latency at all), and synchronous operations. JACK can also be an alternative to pulseaudio for an user that want a professional solution, see {{See also|JACK#ALSA}} - Bridging ALSA and JACK together.
&lt;/div&gt;

&lt;div lang="en" dir="ltr" class="mw-content-ltr"&gt;
Hopefully this small brief section about Jack will give some quick insight about Jack's features, while reserving the details of Jack to a Wiki page specifically focused on Jack.
&lt;/div&gt;

&lt;div lang="en" dir="ltr" class="mw-content-ltr"&gt;
In the meantime, you can take a look at the [https://web.archive.org/web/20220325210326/https://proaudio.tuxfamily.org/wiki/index.php?title=Main_Page Pro-Audio Gentoo Overlay Wiki].
&lt;/div&gt;

=== 权限 ===

&lt;div class="mw-translate-fuzzy"&gt;
如果全局启用了 &lt;code&gt;acl&lt;/code&gt; USE 标记并且正在使用 [[ConsoleKit]](即系统正在使用 “desktop” [[Profile (Portage)|特定配置文件]])对声卡的权限会自动处理。可以使用 {{c|getfacl}} 检查权限:
&lt;/div&gt;

&lt;div class="mw-translate-fuzzy"&gt;
{{Cmd|getfacl /dev/snd/controlC0 {{!}} grep larry|output=
 user:'''larry''':rw-
}}
&lt;/div&gt;

更广泛的解决方案是将您希望能够访问声卡的用户添加到“audio”组:

&lt;div class="mw-translate-fuzzy"&gt;
{{RootCmd|gpasswd -a larry audio}}
{{Cmd|grep audio /etc/group|output=                                                                                                         
audio::18:larry
}}
&lt;/div&gt;

{{Warning|您应该注销并重新登录以使 {{c|alsamixer}} 工作,否则运行 {{c|alsamixer}} 命令会给您错误反馈 “cannot open mixer: No such file or directory”}}

=== 服务 ===

==== OpenRC ====

如果使用 OpenRC 现在使用 {{c|service}} 命令启动 ALSA:

{{RootCmd|rc-service alsasound start}}

要在系统启动时开启 ALSA,请使用 {{c|rc-update}} 将其添加到启动运行级别:

{{RootCmd|rc-update add alsasound boot}}

==== systemd ====

&lt;div lang="en" dir="ltr" class="mw-content-ltr"&gt;
If using systemd, ALSA state will be preserved and restored automatically across system restarts.
&lt;/div&gt;

&lt;div lang="en" dir="ltr" class="mw-content-ltr"&gt;
The status of ALSA can be checked using the {{c|systemctl}} command:
&lt;/div&gt;

{{RootCmd|systemctl status alsa-restore}}

=== 调音控制台 ===

&lt;div lang="en" dir="ltr" class="mw-content-ltr"&gt;
If you can't hear anything, the output channels may be muted. Unmute the channels with the desktop environment's mixer or with {{c|alsamixer}} by selecting the appropriate channels and pressing the {{Key|M}} key to mute or unmute:
&lt;/div&gt;

{{Cmd|alsamixer}}

== 使用 ==

=== 测试扬声器 ===

&lt;div lang="en" dir="ltr" class="mw-content-ltr"&gt;
If everything above is perfect, it should now be able to test the sound card and the speakers. The {{c|speaker-test}} command-line tool from package {{Package|media-sound/alsa-utils}} (this should already be installed as per the previous recommendation).
&lt;/div&gt;

{{Cmd|speaker-test -t wav -c 2}}
 
对于使用 5.1 环绕声系统的配置:

{{Cmd|speaker-test -t wav -c 6 -D surround51}}

使用 {{Key|Ctrl}}+{{Key|C}} 中断测试。

=== 测试麦克风 ===

&lt;div lang="en" dir="ltr" class="mw-content-ltr"&gt;
If needed, select the audio device if no default one is provided and add the &lt;code&gt;--device=hw:0,0&lt;/code&gt; to the incantation of {{c|arecord}}, substituting the CardNumber,DeviceNumber in the integer fields.
&lt;/div&gt;

下面将列出可能的设备。

{{Cmd|arecord --list-devices}}

&lt;div lang="en" dir="ltr" class="mw-content-ltr"&gt;
{{Note|You may also need to unmute the line or microphone channel. Open {{c|alsamixer}} and first select the sound card (i.e. {{Key|F6}}), then press {{Key|F4}} to show the Capture Channels, "left/right cursor keys" to select the "Mic" channel and press {{Key|Space}} to toggle CAPTURE the channel.}}
&lt;/div&gt;

以下将无限期录制直到按下 {{Key|CTRL}}+{{Key|C}},并且提供默认的 8000 Hz 单声道质量录制:

{{Cmd|arecord /tmp/test.wav}}

&lt;div lang="en" dir="ltr" class="mw-content-ltr"&gt;
The following will provide will record for two seconds (--duration=2) using DAT 48000 Hz quality (&lt;code&gt;--format=dat&lt;/code&gt;) and display the curses vumeter in stereo (&lt;code&gt;--vumeter=stereo&lt;/code&gt;) and save to {{Path|/tmp/test.wav}}.
&lt;/div&gt; 

{{Cmd|&lt;nowiki&gt;arecord --channels=1 --duration=2 --format=dat --vumeter=stereo /tmp/test.wav

或者可选地:

{{FileBox|filename=~/.bashrc|lang=bash|1=

  1. Simple convenience wrapper to record then play back a temporary sound file.
  2. Usage: arecord-mic duration

function arecord-mic {

   [[ $1 == *[![:digit:]]* ]] || return
   typeset tmpFile
   tmpFile=$(mktemp --suffix .wav) || return

Notice, arecord cannot record in S24_LE, and is only capable of recording using S16_LE or S32_LE formats. For the human ear, any audio resolutions greater than 24 bit (S24_LE) or 48000Hz are said to be indistinguishable to differentiate using the human ear. Reference Sampling (signal processing) Wikipedia, Audio sampling. Users should also specify channels=1, as all recordings are performed in mono/monaural when typically using the Microphone Input unless recordings are using the stereo Line Input. In order to further encourage arecord to record monaural or only one channel, using the device=plughw:0,0 is further specified. (Alleviates a common problem, microphone/mic playback only occurs on the right or left channels.)

使用 mplayeraplay 播放保存的文件。我通常以“dat”或至少“cd”质量格式录制。在基准测试下 DAT 是最好的。

小贴士

尝试 PaulBredbury 的 asoundrc 文件 中的众多配置选项之一。

故障排除

Firefox 和 YouTube 没有自定义 .asoundrc 的音频,但其他应用程序有

Browsers are sometimes picky about ~/.asoundrc settings. If you're specifying the default audio device (likely given that most computers nowadays have an HDMI A/V output and the analog and HDMI audio outputs are viewed as two separate sound cards), try doing this specifically as follows:

文件 ~/.asoundrc
defaults.pcm.card <number of your default sound card>
defaults.ctl.card <default sound card>
附注
Since version 52, Firefox has made PulseAudio a hard requirement and dropped support for direct output to ALSA. To enable sound in these versions of Firefox enable the pulseaudio USE flag. See PulseAudio requirement breaks Firefox on ALSA-only systems. This limitation does not affect Firefox (version 52 only) built from sources (www-client/firefox). Chromium is also not immune to problem. Both browsers either depend on pulseaudio to set up correct sample rate or in absence of pulseaudio set sample rate to 48000 as defacto standard in sound card world. So if you have 96000 hz sample rate, downgrade it to 48000 and sound will work once again.

声卡仅适用于一个应用程序

Sometimes one app essentially takes over all sound devices. This might even be for performance reasons.

Force the use of dmix instead of direct audio output (which is what most things use by default, such as Adobe Flash [which really means the browser] and Wine).

If the device is card 1 and device 7 (which is the case for Nvidia HDMI for me):

文件 ~/.asoundrc
pcm.dmixed {
    type asym
    playback.pcm {
        type dmix
        ipc_key 5678293
        ipc_perm 0660
        ipc_gid audio

        slave {
            channels 2 # Make 6 or 5.1 channel
            pcm {
                format S16_LE # S32_LE
                rate 48000 # Can also be 44100
                type hw
                card 1 # Your card
                device 7 # Your device
                subdevice 0 # Important?
            }

            period_size 1024
            buffer_size 8192
        }

        bindings {
            0 0
            1 1
# Uncomment below if using 6 channel
#           2 2
#           3 3
#           4 4
#           5 5
        }
    }
    capture.pcm "hw:0"
}

pcm.!default {
    type plug
    slave.pcm "dmixed"
}

Use of ~/.asoundrc is immediate and as long as you are not forcing the use of specific devices in any applications, they either will require a restart or will begin working immediately. One of the best tests is to run Chrome, go to YouTube, open a terminal, run mplayer with an audio or video file and see that you do not get an error about audio (such an error might be 'Device or resource busy').

Missing dialogue (sounds) with 4.0 speakers

If you're using a 4.0 sound card (like an old SB Live!) or 4.0 speakers in general, you may notice that in some games or movies the dialogues are very quiet or even missing. This is because most of those applications/movies support only either 2.0 (stereo) or 5.1 output. In order to achieve surround sound, the 5.1 audio track is used but the two excessive channels are discarded — the center channel (which usually carries dialogues) and subwoofer channel.

The above issue can be circumvented through creating a virtual device which will downmix 5.1 to 4.0, mixing the center and subwoofer channels with other audio channels.

文件 ~/.asoundrc
pcm.downmix {
    type route

    slave {
        # The sound card output to be used
        pcm surround40
        # Real number of output channels
        channels 4
    }

# ttable.A.B G
# where A - input channel
#       B - output channel
#       G - volume gain (1.0 = original)

# Copy channels 0-3
    ttable.0.0 1
    ttable.1.1 1
    ttable.2.2 1
    ttable.3.3 1

# Mix channel 4 (center) into front speakers, and a bit (0.3) into rear ones
    ttable.4.0 1.0
    ttable.4.1 1.0
    ttable.4.2 0.3
    ttable.4.3 0.3

# Mix channel 5 (subwoofer) mostly (0.6) into rear speakers, and a bit (0.3) into front ones
    ttable.5.0 0.3
    ttable.5.1 0.3
    ttable.5.2 0.6
    ttable.5.3 0.6
}

ctl.downmix {
    type hw
    card 0
}

HDMI/SPDIF 5.1 and 7.1 speaker testing

It is stated ALSA's speaker-test utility will not test more then two channel audio over HDMI or SPDIF. For this, you need to use mplayer, as quoted from ALSA's documentation.

Download either a 5.1 channel (FLAC) or 7.1 channel (FLAC) speaker test file:

Play the provided sound file; specifying the HDMI or SPDIF device, PCM file, and number of channels which will likely be either 6 (for 5.1 surround) or 8 (for 7.1 channel surround).

For testing 5.1 channel with mplayer:

user $mplayer -channels 6 "/path/to/downloaded/flac_file.flac" -channels 6

For testing 7.1 channel:

user $mplayer -channels 8 "/path/to/downloaded/flac_file.flac" -channels 8
附注
To test mplayer with a none default device, pass the additional option -ao alsa:device=hw=0.7 where the hw= value is aligned with the appropriate device.

Alternatively testing with VLC media player:

user $cvlc /path/to/downloaded/flac_file.flac

APlay SPDIF/HDMI output has incorrect speaker channels

Now that you know how to use MPlayer to play a speaker test PCM WAV file per "HDMI/SPDIF 5.1 and 7.1 Speaker Testing" above, you now find APlay doesn't output to the speaker channels properly when using SPDIF/HDMI. With HDMI, this is likely caused by the snd_hda_intel HDMI audio module/driver which is used by other manufacturers such as NVidia HDMI aside from just Intel's HDMI hardware. As to why MPlayer does use the correct channels, MPlayer is usually under constant development and manually corrects this issue?

Another problem this solution pertains to, trying to play a 24-bit PCM 2.0 or PCM5.1 WAV files and finding APlay constantly refuses to play the stream, due to incorrect bit rate, etc.

To correct this for ALSA (APlay) with minimal alterations to the PCM streams, we'll need to remap the speaker channels within a ${HOME}/.asoundrc file. Add the following to the bottom of your ${HOME}/.asoundrc file. Also note, the below configuration is for both 5.1 and 7.1 audio, or you could further map/copy the two extra channels to your 5.1 channels incase you do not want to omit the audio from a 7.1 stream.

文件 .asoundrc
pcm.myHDMI {
    type plug
    slave {
        pcm "hw:1,7"
        format S32_LE
        channels 6
    }
    ttable {
        0.0= 1
        1.1= 1
        2.4= 1
        3.5= 1
        4.2= 1
        5.3= 1
        6.6= 1
        7.7= 1
    }
}

It seems that most HDMI to Stereo Receiver connections only stream 16 and 32 bit formats, skipping 24 bit. The above configuration up-mixes any PCM stream to 32 bit when using the pcm.myHDMI profile, as it is quite common to see PCM 2.0 and 5.1 24 bit audio files. It just doesn't seem right to down-mix everything to 16 bit, or use Float as the latter uses more processing power. (Users can also set an alias within their bashrc file for 16 bit or 24 bit incantations as well.)

Test the speaker routing using a surround test PCM file. (See the above previously mentioned "8 Channel Speaker Test".)

user $aplay -D my.HDMI 8Channel.wav

Weak center channel on PCM 5.1 live music

If you have a multi-channel sound track or music with an apparently weak center channel, and the sound track is a live recording; it is possible to map the center channel to the rear channels. Note, the rear channels on live recordings usually contain only the audiance screaming with very little music.

The following incantation of mplayer specifies; your HDMI device of hw:1.7, your PCM 5.1 file, number of channels, the format (not needed if your receiver can natively handle 24 bit and in my case I need to upmix as my Yamaha HDMI receiver can only natively handle 16 or 32 bit audio), and then the mapping. Mapping as follows; specify this is a 6 channel audio stream, with 6 mappings immediately following, copy left front channel to left speaker, copy right channel to right speaker, copy center channel to left rear speaker, copy center channel to right rear speaker, copy center channel to center speaker, and finally copy the subwoofer channel to the subwoofer speaker.

user $mplayer -ao alsa:device=hw=1.7 Music/MyAlbum/PCM51-24bit/01.MyMusic.wav -channels 6 -format s32le -af channels=6:6:0:0:1:1:4:2:4:3:4:4:5:5

See MPlayer's Channel manipulation.

Need to view more detailed information per ALSA stream?

If you need to look at an in-depth illustration of how your program is connecting to ALSA, use the /proc interface. You will need to substitute your relevant card/device details into the command below.

You should see a dump of information regarding the program and useful things like its sample rate(rate) and PID(owner_pid).

user $cat /proc/asound/card2/pcm0p/sub0/*
access: RW_INTERLEAVED
format: S16_LE
subformat: STD
channels: 2
rate: 44100 (44100/1)
period_size: 5513
buffer_size: 22050
card: 2
device: 0
subdevice: 0
stream: PLAYBACK
id: USB Audio
name: USB Audio
subname: subdevice #0
class: 0
subclass: 0
subdevices_count: 1
subdevices_avail: 0
state: RUNNING
owner_pid   : 934
trigger_time: 86393.193574796
tstamp      : 86540.250594985
delay       : 17714
avail       : 4602
avail_max   : 7379
-----
hw_ptr      : 6485052
appl_ptr    : 6502500
tstamp_mode: NONE
period_step: 1
avail_min: 5513
start_threshold: 2147483647
stop_threshold: 22050
silence_threshold: 0
silence_size: 0
boundary: 6206523236469964800

HTML5 does not play in a browser

If there is no sound in any browser used (Firefox, SeaMonkey, Otter Browser, etc.) and ALSA generally works, there is a workaround that might solve this particular issue: try removing the /etc/asound.conf file.

root #mv /etc/asound.conf /etc/asound.conf.old

Restart the browser and test the sound output for HTML5. It might just work now after applying this workaround.

HTML5 does not play in the Firefox browser

Some system motherboards (i.e. Asus Z87-EXPERT) cause Card 0 to be a MID device instead of a PCM device. The same driver module snd_hda_intel is used for both the MID and PCM cards on this motherboard. For some reason Firefox HTML 5 requires Card 0 of the snd_hda_intel no matter how you change it with asoundrc. You can make flash work using the asoundrc file, but HTML 5 audio is silent.

You must remap the PCM device in Linux as card 0 and remove the changes to asoundrc that were added to make Flash work. This wiki page indicates that you should compile the snd_hda_intel driver into the kernel. Using this configuration you must remap the card 0 and card 1 devices using boot parameters instead of a /etc/modprobe.d/alsa.conf file. For example the following kernel command line option will swap the MID and PCM card indicies so that the default card 0 is the PCM card:

snd-hda-intel.index=1,0

附注
The module is named snd_hda_intel, but the boot parameter name is snd-hda-intel.

Laptops with HDMI audio output

Some laptops with an HDMI audio output will map /proc/asound/card0 as HDMI and therefore makes it default output device for applications as stated above in the Firefox section. Another way to remap is to add these two lines to /etc/modprobe.d/alsa.conf

文件 /etc/modprobe.d/alsa.conf
# 此处设置正确的声卡数量。
options snd cards_limit=2
options snd-hda-intel index=1,0

通过检查此命令验证顺序更改

user $cat /proc/asound/cards
 0 [PCH            ]: HDA-Intel - HDA Intel PCH
                      HDA Intel PCH at 0xf2534000 irq 45
 1 [HDMI           ]: HDA-Intel - HDA Intel HDMI
                      HDA Intel HDMI at 0xf2530000 irq 46

此方法仅适用于将 snd-hda-intel 编译为非内置模块的情况

IPC 信号量 - 功能未实现

If you try to run the test procedure, and speaker-test returns an error about a function IPC semaphore not implemented, that is the option to activate in your Kernel :

内核
General setup --->
    [*] System V IPC

耳机插孔不工作

Sometimes to get headset jack working, additional model information is needed for audio driver. For example, in case of Dell Latitude E7470 laptop with snd-hda-intel driver, this needs to be added to /etc/modprobe.d/alsa.conf:

文件 /etc/modprobe.d/alsa.conf
options snd-hda-intel model=headset-mic

More setup information can be found in Linux kernel documentation Documentation/sound/hd-audio/models.rst.

启动时状态恢复出现 udev/alsactl 错误

Due to partitioning, encryption, or having a split /usr system, these errors may appear on boot:

root #journalctl -b | grep alsa
 
(udev-worker)[2594]: controlC2: Process '/usr/sbin/alsactl restore 2' failed with exit code 2.
 
(udev-worker)[2611]: controlC0: Process '/usr/sbin/alsactl restore 0' failed with exit code 2.
 
(udev-worker)[2579]: controlC1: Process '/usr/sbin/alsactl restore 1' failed with exit code 2.

To fix the issue, add TEST=="@sbindir@/alsactl" to the following lines of this file like so:

文件 /lib/udev/rules.d/90-alsa-restore.rules
TEST!="/etc/alsa/state-daemon.conf", TEST=="@sbindir@/alsactl", RUN+="/usr/sbin/alsactl restore $attr{device/number}"
TEST=="/etc/alsa/state-daemon.conf", TEST=="@sbindir@/alsactl", RUN+="/usr/sbin/alsactl nrestore $attr{device/number}"

See these references for further details and discussion.[1][2]

另请参阅

外部资源

References