ALSA and PulseAudio Refresher

Wiki.TerraBase.info
Jump to navigation Jump to search

...just some quick notes on commonly used commands. Sourced from other page and useful when not having used ALSA or PulseAudio for a couple of months when needing to get some stuff accomplished quickly

General

Show information about Audio Devices: aplay -l OR aplay -L

Play via ALSA (forget PulseAudio and MPD): aplay -D hw:0,0 -c 6 BeeGees.wav -vv (...don't forget: service pulseaudio stop)

References

https://www.alsa-project.org/wiki/Asoundrc

https://www.alsa-project.org/alsa-doc/alsa-lib/pcm_plugins.html

Dual Physical Audio Devices

Below are the configuration items for /etc/asound.conf, /etc/pulse/system.pa, and /etc/mpd.conf. Notice how the left and right audio channels are used by each device to provide a stereo sound;

/etc/asound.conf;

pcm.DualSound {
    type multi
    slaves.a.pcm "hw:0,0"
    slaves.a.channels 2
    slaves.b.pcm "hw:1,0"
    slaves.b.channels 2
    bindings.0.slave a
    bindings.0.channel 0
    bindings.1.slave b
    bindings.1.channel 1
}

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



/etc/pulse/system.pa (among other 'generic' directives needed in the file, this is the one specific to Dual Audio, yup, that's it);

load-module module-alsa-sink device=DualSound name=ALSA.DualSound



/etc/mpd.conf (if playing files from MPC / MPD, and note how PulseAudio appends a prefix automatically);

audio_output {
	type            "pulse"
	name            "DualAudio"
	sink		"alsa_output.ALSA.DualSound"
 }

According to documentation on https://www.alsa-project.org/wiki/Asoundrc, the sound synchronization may 'drift' or become unsynchronized after some unknown period of time. But then again, the stereo thing should mask that for quite some time. Plus on that same page they have several examples that just don't work at all, so how much can they be trusted, right? After all, they're just the ones that programmed the darn software.

An Insane Side Story

What if two Audio Cards each support a different default rate?

For example: cat /proc/asound/card0/pcm0p/sub0/hw_params and cat /proc/asound/card1/pcm0p/sub0/hw_params

Card 0;
access: MMAP_INTERLEAVED
format: S16_LE
subformat: STD
channels: 2
rate: 44100 (44100/1)
period_size: 44100
buffer_size: 88200

Card 1; 
access: MMAP_INTERLEAVED
format: S16_LE
subformat: STD
channels: 2
rate: 48000 (48000/1)
period_size: 48000
buffer_size: 96000

Well, executing this command will produce normal play speed: aplay -D hw:0,0 -c 6 BeeGees.wav -vv

But executing this command will produce a 'chipmunkish' play speed: aplay -D hw:1,0 -c 6 BeeGees.wav -vv

How can this be corrected? Hint, it ain't easy as switches like -r (rate) or --rate= and --disable-resample do NOT, NOT, NOT, NOT (get it, it doesn't work) if -D is specified.

What about the 'plug' PlugIn as suggested below;

aplay -D hw:1,0 BeeGees.wav -vv
Playing WAVE 'BeeGees.wav' : Signed 16 bit Little Endian, Rate 44100 Hz, Stereo
Warning: rate is not accurate (requested = 44100Hz, got = 48000Hz)
         please, try the plug plugin 
Hardware PCM card 1 'Plugable USB Audio Device' device 0 subdevice 0
Its setup is:
  stream       : PLAYBACK
  access       : RW_INTERLEAVED
  format       : S16_LE
  subformat    : STD
  channels     : 2
  rate         : 48000
  exact rate   : 48000 (48000/1)
  msbits       : 16
  buffer_size  : 24000
  period_size  : 6000
  period_time  : 125000
  tstamp_mode  : NONE
  tstamp_type  : MONOTONIC
  period_step  : 1
  avail_min    : 6000
  period_event : 0
  start_threshold  : 24000
  stop_threshold   : 24000
  silence_threshold: 0
  silence_size : 0
  boundary     : 1572864000
  appl_ptr     : 0
  hw_ptr       : 0
##########################

How about: aplay -D plug:hw:1,0 BeeGees.wav -vv

SOL baby!

OK, what about using the audio devices name instead of the "hw" number?: aplay -D default:CARD=ICUSBAUDIO7D BeeGees.wav -vv

Wait! Forgot the 'plug' portion: aplay -D plug:default:CARD=ICUSBAUDIO7D BeeGees.wav -vv

Nope, still SOL!

Turns out TWO Colons after -D don't work.

Solution: aplay -D plughw:default:CARD=ICUSBAUDIO7D BeeGees.wav -vv

(from https://raspberrypi.stackexchange.com/questions/69058/difference-between-hwplug-and-hw)

Now here's the insanity of it, in terms of documentation;

aplay --help produces;

Usage: aplay [OPTION]... [FILE]...

-h, --help              help
    --version           print current version
-l, --list-devices      list all soundcards and digital audio devices
-L, --list-pcms         list device names
-D, --device=NAME       select PCM by name
-q, --quiet             quiet mode
-t, --file-type TYPE    file type (voc, wav, raw or au)
-c, --channels=#        channels
-f, --format=FORMAT     sample format (case insensitive)
-r, --rate=#            sample rate
-d, --duration=#        interrupt after # seconds
-s, --samples=#         interrupt after # samples per channel
-M, --mmap              mmap stream
-N, --nonblock          nonblocking mode
-F, --period-time=#     distance between interrupts is # microseconds
-B, --buffer-time=#     buffer duration is # microseconds
    --period-size=#     distance between interrupts is # frames
    --buffer-size=#     buffer duration is # frames
-A, --avail-min=#       min available space for wakeup is # microseconds
-R, --start-delay=#     delay for automatic PCM start is # microseconds 
                        (relative to buffer size if <= 0)
-T, --stop-delay=#      delay for automatic PCM stop is # microseconds from xrun
-v, --verbose           show PCM structure and setup (accumulative)
-V, --vumeter=TYPE      enable VU meter (TYPE: mono or stereo)
-I, --separate-channels one file for each channel
-i, --interactive       allow interactive operation from stdin
-m, --chmap=ch1,ch2,..  Give the channel map to override or follow
    --disable-resample  disable automatic rate resample
    --disable-channels  disable automatic channel conversions
    --disable-format    disable automatic format conversions
    --disable-softvol   disable software volume control (softvol)
    --test-position     test ring buffer position
    --test-coef=#       test coefficient for ring buffer position (default 8)
                        expression for validation is: coef * (buffer_size / 2)
    --test-nowait       do not wait for ring buffer - eats whole CPU
    --max-file-time=#   start another output file when the old file has recorded
                        for this many seconds
    --process-id-file   write the process ID here
    --use-strftime      apply the strftime facility to the output file name
    --dump-hw-params    dump hw_params of the device
    --fatal-errors      treat all errors as fatal
Recognized sample formats are: S8 U8 S16_LE S16_BE U16_LE U16_BE S24_LE S24_BE U24_LE U24_BE S32_LE S32_BE U32_LE U32_BE FLOAT_LE FLOAT_BE FLOAT64_LE FLOAT64_BE IEC958_SUBFRAME_LE IEC958_SUBFRAME_BE MU_LAW A_LAW IMA_ADPCM MPEG GSM S20_LE S20_BE U20_LE U20_BE SPECIAL S24_3LE S24_3BE U24_3LE U24_3BE S20_3LE S20_3BE U20_3LE U20_3BE S18_3LE S18_3BE U18_3LE U18_3BE G723_24 G723_24_1B G723_40 G723_40_1B DSD_U8 DSD_U16_LE DSD_U32_LE DSD_U16_BE DSD_U32_BE
Some of these may not be available on selected hardware
The available format shortcuts are:
-f cd (16 bit little endian, 44100, stereo)
-f cdr (16 bit big endian, 44100, stereo)
-f dat (16 bit little endian, 48000, stereo)

And the MAN page for aplay;

aplay(1) - Linux man page
Name
arecord, aplay - command-line sound recorder and player for ALSA soundcard driver
Synopsis
arecord [flags] [filename]
aplay [flags] [filename [filename]] ...
Description
arecord is a command-line soundfile recorder for the ALSA soundcard driver. It supports several file formats and multiple soundcards with multiple devices. If recording with interleaved mode samples the file is automatically split before the 2GB filesize.
aplay is much the same, only it plays instead of recording. For supported soundfile formats, the sampling rate, bit depth, and so forth can be automatically determined from the soundfile header.

If filename is not specified, the standard output or input is used. The aplay utility accepts multiple filenames.

Options
-h, --help
Help: show syntax.
--version
Print current version.
-l, --list-devices
List all soundcards and digital audio devices
-L, --list-pcms
List all PCMs defined
-D, --device=NAME
Select PCM by name
-q --quiet
Quiet mode. Suppress messages (not sound :))
-t, --file-type TYPE
File type (voc, wav, raw or au). If this parameter is omitted the WAVE format is used.
-c, --channels=#
The number of channels. The default is one channel. Valid values are 1 through 32.
-f --format=FORMAT
Sample format
Recognized sample formats are: S8 U8 S16_LE S16_BE U16_LE U16_BE S24_LE S24_BE U24_LE U24_BE S32_LE S32_BE U32_LE U32_BE FLOAT_LE FLOAT_BE FLOAT64_LE FLOAT64_BE IEC958_SUBFRAME_LE IEC958_SUBFRAME_BE MU_LAW A_LAW IMA_ADPCM MPEG GSM SPECIAL S24_3LE S24_3BE U24_3LE U24_3BE S20_3LE S20_3BE U20_3LE U20_3BE S18_3LE S18_3BE U18_3LE
Some of these may not be available on selected hardware
The available format shortcuts are:
-f cd (16 bit little endian, 44100, stereo) [-f S16_LE -c2 -r44100]
-f cdr (16 bit big endian, 44100, stereo) [-f S16_BE -c2 -f44100]
-f dat (16 bit little endian, 48000, stereo) [-f S16_LE -c2 -r48000]
If no format is given U8 is used.
-r, --rate=#<Hz>
Sampling rate in Hertz. The default rate is 8000 Hertz. If the value specified is less than 300, it is taken as the rate in kilohertz. Valid values are 2000 through 192000 Hertz.
-d, --duration=#
Interrupt after # seconds. A value of zero means infinity. The default is zero, so if this option is omitted then the arecord process will run until it is killed.
-s, --sleep-min=#
Min ticks to sleep. The default is not to sleep.
-M, --mmap
Use memory-mapped (mmap) I/O mode for the audio stream. If this option is not set, the read/write I/O mode will be used.
-N, --nonblock
Open the audio device in non-blocking mode. If the device is busy the program will exit immediately. If this option is not set the program will block until the audio device is available again.
-F, --period-time=#
Distance between interrupts is # microseconds. If no period time and no period size is given then a quarter of the buffer time is set.
-B, --buffer-time=#
Buffer duration is # microseconds If no buffer time and no buffer size is given then the maximal allowed buffer time but not more than 500ms is set.
--period-size=#
Distance between interrupts is # frames If no period size and no period time is given then a quarter of the buffer size is set.
--buffer-size=#
Buffer duration is # frames If no buffer time and no buffer size is given then the maximal allowed buffer time but not more than 500ms is set.
-A, --avail-min=#
Min available space for wakeup is # microseconds
-R, --start-delay=#
Delay for automatic PCM start is # microseconds (relative to buffer size if <= 0)
-T, --stop-delay=#
Delay for automatic PCM stop is # microseconds from xrun
-v, --verbose
Show PCM structure and setup. This option is accumulative. The VU meter is displayed when this is given twice or three times.
-V, --vumeter=TYPE
Specifies the VU-meter type, either stereo or mono. The stereo VU-meter is available only for 2-channel stereo samples with interleaved format.
-I, --separate-channels
One file for each channel. This option disables max-file-time and use-strftime, and ignores SIGUSR1. The stereo VU meter is not available with separate channels.
-P
Playback. This is the default if the program is invoked by typing aplay.
-C
Record. This is the default if the program is invoked by typing arecord.
-i, --interactive
Allow interactive operation via stdin. Currently only pause/resume via space or enter key is implemented.
--disable-resample
Disable automatic rate resample.
--disable-channels
Disable automatic channel conversions.
--disable-format
Disable automatic format conversions.
--disable-softvol
Disable software volume control (softvol).
--test-position
Test ring buffer position.
--test-coef=<coef>
Test coefficient for ring buffer position; default is 8. Expression for validation is: coef * (buffer_size / 2). Minimum value is 1.
--test-nowait
Do not wait for the ring buffer--eats the whole CPU.
--max-file-time
While recording, when the output file has been accumulating sound for this long, close it and open a new output file. Default is the maximum size supported by the file format: 2 GiB for WAV files. This option has no effect if --separate-channels is specified.
--process-id-file <file name>
aplay writes its process ID here, so other programs can send signals to it.
--use-strftime
When recording, interpret %-codes in the file name parameter using the strftime facility whenever the output file is opened. The important strftime codes are: %Y is the year, %m month, %d day of the month, %H hour, %M minute and %S second. In addition, %v is the file number, starting at 1. When this option is specified, intermediate directories for the output file are created automatically. This option has no effect if --separate-channels is specified.
--dump-hw-params
Dump hw_params of the device preconfigured status to stderr. The dump lists capabilities of the selected device such as supported formats, sampling rates, numbers of channels, period and buffer bytes/sizes/times. For raw device hw:X this option basically lists hardware capabilities of the soundcard.
--fatal-errors
Disables recovery attempts when errors (e.g. xrun) are encountered; the aplay process instead aborts immediately.
Signals
When recording, SIGINT, SIGTERM and SIGABRT will close the output file and exit. SIGUSR1 will close the output file, open a new one, and continue recording. However, SIGUSR1 does not work with --separate-channels.
Examples
aplay -c 1 -t raw -r 22050 -f mu_law foobar
will play the raw file "foobar" as a 22050-Hz, mono, 8-bit, Mu-Law .au file.
arecord -d 10 -f cd -t wav -D copy foobar.wav
will record foobar.wav as a 10-second, CD-quality wave file, using the PCM "copy" (which might be defined in the user's .asoundrc file as:
pcm.copy {
  type plug
  slave {
    pcm hw
  }
  route_policy copy
}
arecord -t wav --max-file-time 30 mon.wav
Record from the default audio source in monaural, 8,000 samples per second, 8 bits per sample. Start a new file every 30 seconds. File names are mon-nn.wav, where nn increases from 01. The file after mon-99.wav is mon-100.wav.
arecord -f cd -t wav --max-file-time 3600 --use-strftime %Y/%m/%d/listen-%H-%M-%v.wav
Record in stereo from the default audio source. Create a new file every hour. The files are placed in directories based on their start dates and have names which include their start times and file numbers.
See Also
alsamixer(1), amixer(1)
Bugs
Note that .aiff files are not currently supported.
Author
arecord and aplay are by Jaroslav Kysela <perex@perex.cz> This document is by Paul Winkler <zarmzarm@erols.com>. Updated for Alsa 0.9 by James Tappin <james@xena.uklinux.net>
Referenced By
alsactl(1), speaker-test(1)

And finally the Google search for: "aplay" "man" "plughw" doesn't actually produce any sort of manual or help information, just websites like StackExchange that discuss the issue.

WTF? If it isn't documented how in the world can a reasonable person figure stuff out? Answer? Beat your head against the wall for a couple of hours.