Alsa arch linux кнопки звука

Содержание
  1. Лучшие методы управления звуком в Linux с использованием ALSA, часть 2
  2. Тестирование звуковых каналов
  3. «Раскопки» в звуковых картах
  4. Запись с использованием ALSA
  5. Источники
  6. Sound system (Русский)
  7. Contents
  8. Общие сведения
  9. Драйверы и интерфейс
  10. Звуковые серверы
  11. Шаг 8: Звук
  12. PulseAudio
  13. Advanced Linux Sound Architecture
  14. Contents
  15. Installation
  16. User privileges
  17. ALSA utilities
  18. OSS compatibility
  19. PulseAudio compatibility
  20. ALSA and systemd
  21. ALSA firmware
  22. Unmuting the channels
  23. Unmute with amixer
  24. Unmute with alsamixer
  25. Unmute 5.1/7.1 sound
  26. Enable the microphone
  27. Test your changes
  28. Additional notes
  29. Configuration
  30. Basic syntax
  31. Assignments and Separators
  32. Data types
  33. Operation modes
  34. Nesting
  35. Including configuration files
  36. Set the default sound card
  37. Setting the default sound card via defaults node
  38. Configuring the index order via kernel module options
  39. Select the default PCM via environment variable
  40. Alternative method
  41. Verifying correct sound modules are loaded
  42. Getting S/PDIF output
  43. System-wide equalizer
  44. Using ALSAEqual (provides UI)
  45. Using mbeq
  46. High quality resampling
  47. Upmixing/downmixing
  48. Upmixing
  49. Downmixing
  50. Tips and tricks
  51. Disabling auto mute on startup
  52. Hot-plugging a USB sound card
  53. Simultaneous output
  54. Keyboard volume control
  55. Virtual sound device using snd-aloop
  56. Debugging ALSA
  57. Retrieving the driver state
  58. Reconfiguring input/output ports
  59. Resetting codecs
  60. Correctly detect microphone plugged in a 4-pin 3.5mm (TRRS) jack

Лучшие методы управления звуком в Linux с использованием ALSA, часть 2

Тестирование звуковых каналов

На прошлой неделе мы изучили, как настроить звуковые карты для воспроизведения с использованием ALSA. Это легко, это работает на всех системах Linux, не создает конфликтов, не вносит задержек и не требует использования системы X Window. Сегодня мы приступим к изучению использования ALSA для записи, и расскажем как протестировать нашу звуковую систему.

Быстрый и не очень хороший путь увидеть, что звук работает — это направить содержимое файла в dev/dsp:

Более правильный способ — использование набора alsa-utils, который включает некоторое количество полезных команд для тестирования вашей установки. Команда speaker-test тестирует каналы динамиков. Вот пример команды для простой стерео-установки с двумя динамиками:

В ходе тестирования вы должны слышать приятный женский голос, говорящий «Front left, front right». В данном примере -c2 означает два канала, а -l2 означает запуск теста два раза.

Будьте внимательны с нумерацией каналов — номера динамиков выводимые командой speaker-test начинаются с нуля, в то время как номер опции -s начинается с единицы. Система требует точности!

LFE (Low Frequency Effects) означает низкочастотные эффекты, которые обычно подразумевают работу вашего сабвуфера. Естественно, они более сложные, чем те, что описывались выше (для более подробной информации смотрите « Что такое LFE канал? »).

«Раскопки» в звуковых картах

Как вы можете узнать какой тип вывода поддерживает ваша звуковая карта? Команда aplay вам поможет:

Прим.переводчика: перевод сообщений на русский язык в выводе команды вы, естественно, не увидите.

.asoundrc. Просто, но эффективно:

Теперь, вместо aplay -D hw:1,0 test.wav можно использовать aplay -D headset test.wav. То есть, происходит замена идентификаторов ядра (0,0- 1,0) именами (V8237, Headset) , поскольку идентификаторы ядра могут меняться, и особенно это касается udev устройств.

Запись с использованием ALSA

Для того, чтобы остановить выполнение команды, нажмите Ctrl+C.

Напоследок, несколько полезных советов.

Чтобы узнать версию ALSA, запустите cat /proc/asound/version.

Вышеприведенные примеры относятся к интегрированной в мою низкобюджетную материнскую плату ESC звуковой подсистеме. Она поддерживает цифровой выход (S/PDIF = Цифровой интерфейс Sony-Philips) в дополнение к аналоговому. Тем не менее, я не могу его использовать — на материнской плате нет разъемов.

Будьте внимательны при покупке звуковых карт, поскольку часто можно встретить заявления такого рода: «24-битный цифровой звук!». Все компьютерные звуковые карты поддерживают цифровой звук, это их основная работа — преобразовывать цифровые аудио-файлы для аналоговых динамиков. Но если вы действительно желаете приобрести звуковую карту с цифровым выходом для цифровых динамиков — внимательно прочитайте спецификацию, чтобы быть уверенным, что получаете 100% цифровое качество на самом деле.

Источники

  • man alsamixer
  • man aplay/arecord
  • man speaker-test
  • HOWTO Dolby Digital and DTS
  • ALSA , со множеством полезной документации
  • Неофициальная, но очень полезная ALSA Wiki

Карла Шредер — автор книг «Linux. Сборник рецептов» и недавно изданной «Сборник сетевых рецептов», а так же постоянный автор статей на LinuxPlanet.

Источник

Sound system (Русский)

Эта статья рассказывает о базовом управлении звуком. Для получения информации о более сложных темах см. статью Профессиональное аудио.

Contents

Общие сведения

Звуковая система Arch Linux состоит из нескольких уровней:

  • Драйверы и интерфейс — поддержка и взаимодействие с аппаратным обеспечением
  • Usermode API (библиотеки) — требуются и используются приложениями
  • (опционально) Звуковые серверы в пользовательском режиме — находят лучшее применение в сложных системах, требующих одновременной работы нескольких аудиоприложений и незаменимы для более продвинутых возможностей, например, профессионального аудио.
  • (опционально) Звуковые фреймворки — более высокоуровневые программные окружения, не связанные с серверными процессами

Базовая установка Arch Linux включает в себя звуковую систему ядра (ALSA), также можно установить множество утилит для управления ALSA из официальных репозиториев. Если требуются дополнительные возможности, вы можете сменить его на OSS или выбрать другой звуковой сервер.

Драйверы и интерфейс

  • ALSA — компонент ядра Linux, содержащий драйверы устройств и обеспечивающий наиболее низкоуровневую поддержку звукового аппаратного обеспечения.

https://www.alsa-project.org/wiki/Main_Page || входит в состав ядра по умолчанию

  • Open Sound System (OSS) — альтернативная звуковая архитектура для Unix- и POSIX-совместимых систем. OSS 3-ей версии была основной звуковой системой Linux и включалась в ядро, но была заменена на ALSA в 2002 году, когда 4-ая версия OSS стала проприетарным ПО. OSSv4 вновь стала свободным ПО в 2007, когда 4Front Technologies опубликовали её исходные коды и разместили их под лицензией GPL. OSS не поддерживает такое же множество устройств как ALSA, но в некоторых случаях работает лучше.

http://www.opensound.com/ || ossAUR

Звуковые серверы

  • PulseAudio — очень популярный звуковой сервер, использующийся большинством современных приложений для Linux. Очень хорошо работает с несколькими одновременными потоками аудио и может использоваться по сети. Также PulseAudio легко настраивается — зачастую достаточно только установить пакет.

https://www.freedesktop.org/wiki/Software/PulseAudio/ || pulseaudio

The factual accuracy of this article or section is disputed.

Источник

Шаг 8: Звук

Есть множество путей настроить вывод звука. Я выделю три: ALSA, OSS и PulseAudio.

Я опишу эти технологии, но рекомендую на первое время оставить ALSA. Этот материал будет полезен если определенное приложение потребует OSS или PulseAudio.

ALSA — Advanced Linux Sound Architecture. Данный звуковой интерфейс в Ubuntu 7.10 установлен и настроен, так что проблем с его использованием нет.
Этот интерфейс стандартный и рекомендуемый для Ubuntu, поэтому на первое время его можно оставить.

OSS — Open Sound System. Один из стандартных интерфейсов воспроизведения и захвата звука в Linux.
Этот интерфейс устаревший, ему на смену пришел ALSA. Ставить его следует лишь для совместимости со старым софтом.

1. Убедимся что стоят пакеты: build-essential, gcc, make, binutils, libssl-dev, linux-headers-`uname -r`.

sudo apt-get install build-essential gcc make binutils libssl-dev linux-headers-`uname -r`

2. Выбираем, качаем и устанавливаем пакет (обычно x86 (DEB)) по ссылке www.4front-tech.com/download.cgi

При этом в процессе установки инсталлятор может сказать что-то вроде:

ERROR: Module snd_pcm is in use by snd_ice1724,snd_intel8x0,snd_ac97_codec,snd_ak4114
ERROR: Module snd_pt2258 is in use by snd_ice1724
ERROR: Module snd_i2c is in use by snd_ice1724,snd_pt2258
ERROR: Module snd_ak4xxx_adda is in use by snd_ice1724,snd_ice17xx_ak4xxx
ERROR: Module snd_mpu401_uart is in use by snd_ice1724
ERROR: Module snd_rawmidi is in use by snd_mpu401_uart
ERROR: Module snd_timer is in use by snd_pcm
ERROR: Module snd_seq_device is in use by snd_rawmidi
ERROR: Module snd_page_alloc is in use by snd_intel8x0,snd_pcm
Failed to disable conflicting sound drivers
Reboot and try running soundon again

Also check that you have not compiled sound support statically
into the kernel.

4. Спокойно перезагружаемся и идём в BIOS — очень желательно отключить встроенный звуковой кодек — так как может возникнуть следующая проблема:

— Detected M Audio Revolution 5.1
Detected Nvidia nForce2
Detected Generic USB audio device (BETA)
Detected OSS Transparent Virtual Mixing Architecture
— Starting Open Sound System
ERROR: Module snd_intel8x0 is in use
ERROR: Module snd_ac97_codec is in use by snd_intel8x0
ERROR: Module snd_pcm is in use by snd_intel8x0,snd_ac97_codec
ERROR: Module snd_timer is in use by snd_pcm
ERROR: Module snd_page_alloc is in use by snd_intel8x0,snd_pcm

5. После перезагрузки выполняем в терминале:

Вывод будет похож на:

OSS 4.0 (b1009/200711130545) © 4Front Technologies 1996-2007

This OSS version will expire after: May 2008

Audio devices:
0: M Audio Revolution 5.1 front out (OUTPUT)
1: M Audio Revolution 5.1 c/l out (OUTPUT)
2: M Audio Revolution 5.1 surround out (OUTPUT)
3: M Audio Revolution 5.1 digital out (OUTPUT)
4: M Audio Revolution 5.1 analog in (INPUT)

Mixers:
0: M Audio Revolution 5.1

6. Проверим работу

Откроем файл /usr/lib/oss/lib/flashsupport.c с правами администратора, закомментируем двумя слэшами (//) строку «#define OPENSSL» и сохраним.

Идем в папку /usr/lib/oss/lib
cd /usr/lib/oss/lib

Компилируем
sudo cc -shared -m32 -O2 -Wall -Werror -lssl flashsupport.c -o /tmp/libflashsupport.so

Инсталлируем
sudo install -s /tmp/libflashsupport.so /usr/lib/

И можем создать ссылку для Firefox
sudo ln -s /usr/lib/libflashsupport.so /usr/lib/firefox/plugins

Здесь была рассмотрена установка retail-версии. Она бесплатна, но требует обновления раз в полгода командой:

PulseAudio

PulseAudio это не просто интерфейс вывода звука. Это целый сервер звука. С его помощью звук можно передавать по каналам связи и воспроизводить на удаленных машинах.
Этот интерфейс очень перспективный. Некоторое современное ПО уже требует его.

Ставится он легко:

1. Устанавливаем необходимые пакеты:

sudo apt-get install «pulseaudio-*» paman padevchooser paprefs

2. Чтобы звук работал в flash, надо скачать и поставить пакет www.paulbetts.org/projects/libflashsupport_1.0

3. Редактируем файл настроек ALSA (sudo gedit /etc/asound.conf), пишем туда:

ctl.pulse <
type pulse
>

pcm.!default <
type pulse
>
ctl.!default <
type pulse
>

4. Открываем Система→Настройки→Звук и на вкладке «Звуки» включаем опцию «Включить програмное смешивание звука (ESD)».

5. Добавляем всех пользователей в группу pulse-access. Открываем Система→Администрирование→Пользователи и группы, Управление группами и выбираем группу pulse-access, куда добавляем всех пользователей, которые будут использовать аудиосервер.

6. Запускаем PulseAudio

Чтобы быть в курсе моих статей, можно подписаться на RSS-канал.

Источник

Advanced Linux Sound Architecture

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.

Contents

Installation

ALSA is a set of built-in Linux kernel modules. 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.

User privileges

Usually, 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, however this is not recommended by default (see note below).

ALSA utilities

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

If you need high quality resampling install the alsa-plugins package to enable upmixing/downmixing and other advanced features.

OSS compatibility

ALSA has some ability to intercept OSS calls and re-route 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. Then load the snd-seq-oss , snd-pcm-oss and snd-mixer-oss kernel modules to enable OSS emulation.

PulseAudio compatibility

apulse AUR lets you use ALSA for applications that support only PulseAudio for sound. Usage is simply $ apulse yourapplication .

ALSA and 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). Neither will run by default, as they rely on some conscious decisions by the user to know which method should be preferred. The options are as follows:

  • alsa-restore.service Reads /var/lib/alsa/asound.state on boot and writes updated values on shutdown, granted it is already present by having ran alsactl store at some point
  • alsa-state.service (Re-)Starts alsactl in daemon mode to continouously keep track of, and persist, volume changes, again under the condition that the user has consciously started alsactl daemon at least once

Both methods are mutually exclusive and you can decide for one of the two approaches depending on your requirements, for further information see alsactl(1)

You can check their status using systemctl .

ALSA firmware

The alsa-firmware package contains firmware that may be required for certain sound cards (e.g. Creative SB0400 Audigy2).

sof-firmware and alsa-ucm-conf are required for few newer laptop models (end of 2019/2020) which implement their drivers with firmware provided by the Sound Open Firmware project.

Unmuting the channels

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

Unmute with amixer

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

Unmute with alsamixer

Unmuting the sound card can be done using 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 ← and → keys and unmute them by pressing the m key.

Use the ↑ 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.

Unmute 5.1/7.1 sound

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)

Enable the microphone

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.

Test your changes

Next, test to see if sound works:

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

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

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

If that does not work, consult the #Configuration section or the /Troubleshooting page.

Additional notes

  • 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. For the Soundblaster Audigy LS mute the channel labeled IEC958 .
  • 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.

Configuration

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

Basic syntax

ALSA configuration files follow a simple syntax consisting of hierarchical value to parameter (key) assignments. The syntax is also shown in [2].

Assignments and Separators

Assignments define a value of a given key. There are different assignment types and styles available.

Separators are used to indicate the start and end of an assignment, but using commas or whitespace is also possible.

Compound assignments use braces as separators.

For easier reading, it is recommended to use first style for definitions including more than three keys.

Array definitions use brackets as separators.

Everything depends on user preferences when it comes to different styles of configuration, however one should avoid mixing different styles. Further information on basic configuration can be found in [3].

Data types

ALSA uses different data types for parameter values, which must be set in the users respective configuration file. Some keys accept multiple data types, while most do not. A list of configuration options and their respective type requirements for PCM plugins can be found in [4].

Operation modes

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

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.

An example of setting default device using «defaults» node

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.

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.

Nesting

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

Including configuration files

Set the default sound card

Setting the default sound card via defaults node

To put 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.

Configuring the index order via kernel module options

If your sound card order changes on boot, you can specify their order in any file ending with .conf in /etc/modprobe.d ( /etc/modprobe.d/alsa-base.conf is suggested). For example, if you want your mia sound card to be #0:

Use $ cat /proc/asound/modules to get the loaded sound modules and their order. This list is usually all that is needed for the loading order. Use $ lsmod | grep snd to get a devices & modules list. This configuration assumes you have one mia sound card using snd_mia and one (e.g. onboard) card using snd_hda_intel .

You can also provide an index of -2 to instruct ALSA to never use a card as the primary one. Distributions such as Linux Mint and Ubuntu use the following settings to avoid USB and other «abnormal» drivers from getting index 0 :

These changes require a system reboot.

Select the default PCM via environment variable

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:

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

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 program 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

Alternative method

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

/.asoundrc or if user deliberately wants to address sound card directly (digital output through eic958 or dedicated music server for example).

For example, the last entry in this list has the card ID 2 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.

In most cases it is recommended to use sound card names instead of number references. Card names are easier to grasp, and also overcomes the boot order problem. Therefore the following would be correct for the above example.

To get valid ALSA card names, use aplay:

Alternatively use cat, which might return unused devices:

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 (MPlayer etc.). You can also test with a command like aplay.

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

Verifying correct sound modules are loaded

You can assume that udev will autodetect your sound properly. You can check this with the command:

If the output looks similar, your sound drivers have been successfully autodetected.

You might also want to check the directory /dev/snd/ for the right device files:

If you have at least the devices controlC0 and pcmC0D0p or similar, then your sound modules have been detected and loaded properly.

If this is not the case, your sound modules have not been detected properly. To solve this, you can try loading the modules manually:

  • Locate the module for your sound card: ALSA Soundcard Matrix The module will be prefixed with ‘snd-‘ (for example: snd-via82xx ).
  • Load the module.
  • Check for the device files in /dev/snd (see above) and/or try if alsamixer or amixer have reasonable output.
  • Configure snd-NAME-OF-MODULE and snd-pcm-oss to load at boot.

Getting S/PDIF output

S/PDIF is a digital audio interface often used to connect a computer to a digital amplifier (such as a home theatre with 5.1/7.1 surround sound).

Depending on what shell you use, add the following line to your shell’s configuration file:

You can see the name of your card’s digital output with:

System-wide equalizer

Using ALSAEqual (provides UI)

Install the alsaequal AUR package. Also install lib32-alsaequal AUR for 32-bit application support.

After installing the package, add the following to your ALSA configuration file:

And you are ready to change your equalizer using command

Note that configuration file is different for each user (until not specified else) it is saved in

/.alsaequal.bin . so if you want to use ALSAEqual with mpd or another software running under different user, you can configure it using

or for example, you can make a symlink to your .alsaequal.bin in his home directory.

Managing ALSAEqual states

Configure the equalizer as usual with

When you are satisfied with the state, you may give it a name («foo» in this example) and save it:

The state «foo» can then be restored at a later time with

This however only restores

/.alsaequal.bin . You then have to update the equalizer by alsamixer -D equal .

You can thus create different equalizer states for games, movies, music genres, VoIP apps, etc. and reload them as necessary.

See the project page and the help message for more options.

Using mbeq

Install the alsa-plugins , ladspa and swh-plugins packages if you do not already have them.

If you have not already created either an

/.asoundrc or a /etc/asound.conf file, then create either one and insert the following:

High quality resampling

When software mixing is enabled, ALSA is forced to resample everything to the same frequency (48 kHz by default when supported). By default, it will try to use the speexrate converter to do so, and fallback to low-quality linear interpolation if it is not available[6]. Thus, if you are getting poor sound quality due to bad resampling, the problem can be solved by simply installing the alsa-plugins package.

For even higher quality resampling, you can change the default rate converter to speexrate_medium or speexrate_best . Both perform well enough that in practice it does not matter which one you choose, so using the best converter is usually not worth the extra CPU cycles it requires.

To change the default converter place the following contents in your

/.asoundrc or /etc/asound.conf :

Upmixing/downmixing

Upmixing

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

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:

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:

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.

Downmixing

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:

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.

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

Tips and tricks

Disabling auto mute on startup

Auto-Mute Mode can be configured on startup with amixer . For example, to disable it:

Alternatively, the graphical interface can be utilized through alsamixer . In order to save any modifications, use:

Hot-plugging a USB sound card

Simultaneous output

You might want to play music via external speakers connected via mini jack and internal speakers simultaneously. This can be done by unmuting Auto-Mute item using alsamixer or amixer :

and then unmuting other required items, such as Headphones, Speaker, Bass Speaker.

Keyboard volume control

Map the following commands to your volume keys: XF86AudioRaiseVolume , XF86AudioLowerVolume , XF86AudioMute

To raise the volume:

To lower the volume:

To toggle mute/unmute of the volume:

Virtual sound device using snd-aloop

You might want a jack alternative to create a virtual recording or play device in order to mix different sources, using the snd-aloop module:

List your new virtual devices using:

now you can for example using ffmpeg:

In the hw:R,W,N format R is your virtual card device number, W 1 recording devices 0 for writing, N is your sub device you can use all the virtual devices available and play/stop using applications like mplayer:

Another thing you could do with this approach, is using festival to generate a voice into a recording stream using an script like this:

Debugging ALSA

Retrieving the driver state

The alsa-utils package also contains the alsa-info.sh command, which can be used to gather detailed data on the ALSA driver and user-space state.

Reconfiguring input/output ports

The alsa-tools package contains the hdajackretask tool, which can be used (on Intel HDA cards) to reconfigure the sound card input/output ports; for instance, to turn a microphone jack into a headphone jack.

Resetting codecs

The ALSA driver can fully reconfigure attached codecs (the parts of the sound system that actually process audio streams), by doing:

Before doing this, all processes using the ALSA driver (such as Pulseaudio or JACK) must be stopped.

Correctly detect microphone plugged in a 4-pin 3.5mm (TRRS) jack

On some modern laptops you may have a combined 3.5mm headset jack, instead of two separated ones, which may not be correctly detected by default. To make ALSA correctly detect plug-in status on your 3.5mm jack, you could put the following line into your /etc/modprobe.d/alsa-base.conf :

For complete list of options to put in your_model_setting , see HD-Audio Codec-Specific Models or its source located at /usr/lib/modules/$(uname -r)/build/Documentation/sound/hd-audio/models.rst (provided by the linux-docs package).

Tested with Gigabyte Aero15 2017 (P65 Model), with ALC255 and set model to dell-headset-multi .

Источник

Читайте также:  Драйвера для asus p5b для windows 10
Оцените статью