Compare commits

...

61 Commits

Author SHA1 Message Date
Lars Immisch
f25c8243dc Update changes for release
[Revisionist Note] This commit was originally c6a0c80, still available
on the main-pre-rewrite branch. The 0.10.0 tag used to point to it.
2024-02-02 11:33:22 +01:00
Lars Immisch
073d708bd1 Remove trailing whitespace in CHANGES.md 2024-02-02 09:52:11 +01:00
Oswald Buddenhagen
946694d263 add PCM.state() and associated enum values
in principle, the state is already available from info(), but that's a
rather heavy function for something one might want to query often.

a practical use case might be checking whether a playback stream is done
draining, for example.
2023-03-02 00:41:01 +01:00
Oswald Buddenhagen
574f78939d add PCM.drain()
for playback, this allows making sure that all written frames are
played, without using an external delay.

in principle, it's also usable for capture, but there isn't really a
practical reason to do so, as simply discarding excess captured frames
has no real cost.
2023-03-02 00:41:01 +01:00
Oswald Buddenhagen
17d171c1a5 make period count configurable
the period count is just as important for playback latency as the period
size, so it makes no sense to have only one of them configurable.

as a drive-by, fix up the handling of periods in info() & dumpinfo().
2023-03-02 00:41:01 +01:00
Oswald Buddenhagen
de2fc3c992 bump (minor) version
we're about to add new features.
2023-03-02 00:41:01 +01:00
Oswald Buddenhagen
c2a6b6e583 reshuffle XRUN recovery somewhat
perform it prior to invoking read()/write() if necessary, not right
after a failure event. this makes things more uniform and predictable.

we don't use snd_pcm_recover() any more, as we used it only for the
EPIPE case anyway, which boils down to snd_pcm_prepare() exactly.
handling ESTRPIPE as well might be desirable, but that's a separate
consideration.
2023-03-02 00:41:01 +01:00
Oswald Buddenhagen
da7d04e2fd reduce scope of GIL releases
it's pointless to enclose snd_pcm_close() and snd_pcm_pause(), as these
calls don't sleep.
2023-03-02 00:41:01 +01:00
Oswald Buddenhagen
1c1af45a7f use data types closer to those of ALSA
this removes lots of casts around snd_pcm_hw_params_get_*() calls

we could go further with that to make the code clean if we enabled all
the warnings, but it doesn't seem worth the effort.
2023-03-02 00:41:01 +01:00
Oswald Buddenhagen
9b773b48d6 purge pydoc from the source
it's been obsolete for a *long* time, and having it redundantly to the
rst sources is bad hygiene. it still contained some useful info, which
has been transplanted to the rst source in the previous commit.
2023-03-02 00:41:01 +01:00
Oswald Buddenhagen
b05efa0ad6 add some best practices to the docu
addresses #110, among other things.
2023-03-02 00:41:01 +01:00
Oswald Buddenhagen
4e098da908 add missing and update incorrect/outdated documentation
for clarity, this includes docs which were previously omitted
(presumably) intentionally, but mark them as comments.

the getrec() and getmute() functions' docs are moved around, so they
appear in pairs with their set*() counterparts, like the *volume() ones
already did.

notably, this also fixes the docu of PCM_FORMAT_U8, which closes #104.
2023-03-02 00:41:01 +01:00
Oswald Buddenhagen
c266d302e0 improve terminology document
mention xruns, and rework the definition of periods: concentrate on
relevant information, and remove the misinformation about period size
reduction being not that bad (pedantically, an application could run
somewhat asynchronously to the interrupts by using some timer, and
therefore actually save some of the overhead, but why would one use a
small period size in the first place then?).

also, language and formatting fixes.
2023-03-02 00:41:01 +01:00
Oswald Buddenhagen
b094ac096b formatting/language fixes in introduction document 2023-03-02 00:41:01 +01:00
Oswald Buddenhagen
46b91980e0 unify line spacing in .rst files
one empty line, except for high-level sections, which get two.

while at it, trim whitespace on otherwise empty lines.
2023-03-02 00:41:01 +01:00
Oswald Buddenhagen
9ab4f721d6 remove bogus markup from the documentation
the poll objects are linked properly in a different way, and the
footnote appears outdated.
2023-03-02 00:41:01 +01:00
Oswald Buddenhagen
a967b7db78 drop some pointless comments from the tex => sphinx conversion
amends 5c2a00655.
2023-03-02 00:41:01 +01:00
Oswald Buddenhagen
01a444ac21 add new high-speed samples rates
closes #89 (but alsa doesn't support 768khz yet).
2023-03-02 00:41:01 +01:00
Oswald Buddenhagen
8bcb7ba626 remove redundant snd_pcm_hw_params_any() call
we just called it (and even error-checked it) a few lines above.
2023-03-02 00:41:01 +01:00
Oswald Buddenhagen
9dc0fc2fd3 fix deprecation warning about PyUnicode_AsUnicode()
converting to ascii for the purpose of comparison is inefficient.
2023-03-02 00:41:01 +01:00
Oswald Buddenhagen
4318b63912 fix deprecation warning about PyEval_InitThreads()
PyEval_InitThreads is a no-op in since python 3.9.
2023-03-02 00:41:01 +01:00
Oswald Buddenhagen
a7b9d617b2 fix crashes when accessing already closed devices
PCM.htimestamp() gets the usual exception emission,
Mixer.close() gets a "double invocation" check like PCM.close() has.
2023-03-02 00:41:01 +01:00
Oswald Buddenhagen
379fc05b5e fix memory handling in mixer access error paths
in case of error, alsamixer_new() would leak the object, while
alsamixer_list() might crash due to a null pointer.

as a drive-by, make alsamixer_gethandle() `static`.
2023-03-02 00:41:01 +01:00
Oswald Buddenhagen
dff8ef031f fix memory leaks in *_polldescriptors()
the calloc'd pollfd arrays were not freed.
2023-03-02 00:41:01 +01:00
Oswald Buddenhagen
8ea9470454 fix draining/closing, take 2
commit 8abf06be introduced a pause() prior to draining, in an attempt
to work around clearly broken pulseaudio client behavior for capture
streams (drain() is supposed to imply a stop).

but as the workaround was also applied to playback streams, it would
cause nasty "clicks", as the stream would (obviously) stop before being
resumed for draining.

but draining is actually pointless for capture streams, as we're closing
right afterwards, so the samples are lost anyway.

what's more, destructors are not supposed to wait for anything, so
draining in alsapcm_dealloc() was wrong to start with. so we remove it.
note that this is a minor behavior change, which is reflected by the
adjustment of the playback test to have an explicit close() at the end.

finally, close() was also affected by the pulseaudio bug (which was not
addressed before), so there we make draining exclusive to playback
streams.
2023-03-02 00:35:02 +01:00
Ronald van Elburg
19c9ba3ed9 Fix issue #104 : Update description of PCM_FORMAT_U8: Unsigned 8 bit samples for each channel 2022-11-27 01:56:36 +01:00
Ronald van Elburg
b2f0466dd2 First version documentation PCM.info() method. (#119)
* First version documentation PCM.info() method.

* Add reference to documentation to docstring for PCM.info() method.

* Add extra fields to info dict:
  card_no                      *index of card*                   integer  (negative indicates device not associable with a card)
   device_no                    *index of PCM device*             integer
   subdevice_no                 *index of PCM subdevice*          integer
and update documentation accordingly.

Co-authored-by: Ronald van Elburg <Ronald@SoundAppraisal.eu>
2022-11-26 19:08:32 +01:00
Lars Immisch
6317d9addc Extend name on get_enum (#114) 2022-05-23 09:37:40 +02:00
Lars Immisch
2432089759 Allow longer device names. Closes #114 2022-05-22 22:43:55 +02:00
Lars Immisch
279760add5 Prepare release 0.9.2 2022-05-06 21:33:41 +02:00
Portia Stephens
59a712c486 alsamixer_getvolume: Fix incorrect parenthesis (#112)
* alsamixer_getvolume: Fix incorrect parenthesis

The pcmtypeobj check is overriding the pcmtype if the object is not NULL
or Py_None, making it impossible to get the playback volume. Fix the
paranthesis so that pcmtype is only overwritten when pcmtypeobj is not
set.

* Fix indentation format

Fix the indentation format to match the rest of the project.1

Co-authored-by: Portia <portia.stephens@biamp.com>
2022-05-06 21:28:36 +02:00
Lars Immisch
dfda54642d Prepare 0.9.1 2022-05-03 20:04:26 +01:00
Chris Diamand
3f6fb9844d Support decibel, percentage, and raw volumes in getvolume, setvolume, and getrange (#109)
* Use `pcmtype` keyword for range

Update methods that accept a `direction` argument (i.e.
capture/playback) to get this via positional _or_ keyword arguments.

Code using keyword arguments can be more robust; however the main reason
for this change is to prepare the way for an extra `units` argument to
many of these methods.

Update documentation to consistently use `pcmtype` instead of
a mixture of that and `direction`.

* Support units
2022-03-28 21:46:40 +02:00
Lars Immisch
4d9f6e5b50 Merge pull request #108 from st8ed/fix-polldescriptors
Fix polldescriptors() data types
2022-01-25 15:17:39 +01:00
Kirill Konstantinov
40a4a36b1d Fix polldescriptors() data types 2022-01-25 14:23:21 +03:00
Lars Immisch
38ea69bbaa Merge pull request #100 from soundappraisal/feature_timestamp_mode_and_type
Feature timestamp mode and type
2021-04-12 12:30:23 +02:00
Ronald van Elburg
c8f3916337 On phys_from_sound: Small memory management fixes and code simplification. And add documentation on new functionality. 2021-04-11 15:16:03 +02:00
Ronald van Elburg
f19af8eba0 Remove recordtestchanges. 2021-04-07 12:12:10 +02:00
Ronald van Elburg
b8980d992b Remove recordtestchanges. 2021-04-07 12:10:21 +02:00
Ronald van Elburg
ebd2b5359d Add function to set timestamp mode and type. Add a function to get the alsa version. 2021-04-07 11:59:16 +02:00
Ronald van Elburg
c5f22fd7e0 Second version enable timestamps 2021-04-06 22:48:17 +02:00
Ronald van Elburg
3c3f0af74a First version enable timestamps 2021-04-06 14:31:45 +02:00
Ronald van Elburg
17f3b440cc Show new functions in recordtest.py 2021-04-06 09:09:49 +02:00
Lars Immisch
b2a303121a Merge pull request #98 from soundappraisal/add_timestamp_function
Add timestamp_raw function
2021-04-04 16:27:26 +02:00
Ronald van Elburg
3168833b4e Merge remote-tracking branch 'upstream/master' into add_timestamp_function
# Conflicts:
#	alsaaudio.c
2021-04-02 22:54:18 +02:00
Lars Immisch
c74669850b Merge pull request #92 from soundappraisal/pcm_info_function
Add an PCM.info function: returns pcm properties as a dict
2021-04-02 20:57:15 +02:00
Ronald van Elburg
1a4c0541d7 Change name timestamp_raw fuinction to htimestamp to follow the convention used in the rest of the library: that's the current convention (prefix the name with alsapcm_ for PCM methods). 2021-04-02 13:42:51 +02:00
Ronald van Elburg
e6a6445375 Move creation of dictionary to a point after error handling, when it is relatively certain that the function will succeed.
(cherry picked from commit 1820716a4bc018bb903b95bcf5d7cf83a5ebda9c)
2021-04-02 13:24:55 +02:00
Ronald van Elburg
97f2abcb30 Remove debugging print statement.
(cherry picked from commit dcc43f3da7bf4d083cc6cab18ae464261fadc53f)
2021-04-02 13:24:55 +02:00
Ronald van Elburg
a53ffd0d4f Fix potential memory leaks on new info function.
(cherry picked from commit ade9dd5923edd65c1fcdf2298e8ad024daf66e2a)
2021-04-02 13:24:55 +02:00
Ronald van Elburg
da71e01f9c Remove unused code from timestamp_raw function. 2021-03-31 16:27:55 +02:00
Ronald van Elburg
f6736ec43a first version timestamp function
(cherry picked from commit 21d0527c7b91723b3bfc87ea889bd599dff12576)

# Conflicts:
#	alsaaudio.c
2020-11-02 19:32:34 +01:00
Ronald van Elburg
e48b294b84 PCM.info function: added format, mode and type fields. Also added a doc string describing the info function. 2020-10-28 22:01:04 +01:00
Lars Immisch
d037297632 Merge pull request #91 from soundappraisal/master
Fix #51: Only return valid part of the buffer in the read function
2020-10-27 12:47:36 +01:00
Ronald van Elburg
c8e7261e94 Add an PCM.info function returning the information now printed by dumpinfo as a dictionary. Removed double entry from dumpinfo. 2020-10-27 12:41:59 +01:00
Ronald van Elburg
5c481b4094 Fix #51: Only return valid part of the buffer in the read function; avoid unnecesssary work by only changing size when needed 2020-09-30 15:58:19 +02:00
Ronald van Elburg
1e3c7f3fd0 Fix #51: Only return valid part of the buffer in the read function 2020-09-30 15:11:10 +02:00
Lars Immisch
0ae60f80f3 Better pcm_type deduction in alsamixer_getvolume
Closes #87
2020-07-16 23:36:50 +02:00
Lars Immisch
4018ab4f6c Fix copypasta. 2020-07-16 23:36:12 +02:00
Lars Immisch
07f84a8e95 Move CHANGES to markdown, remove NOTES.md (doc/README.md replaces it) 2020-07-13 22:27:06 +02:00
Lars Immisch
d83e829de1 Formatting and fixed upload description. 2020-07-13 22:18:32 +02:00
14 changed files with 1193 additions and 761 deletions

5
.gitignore vendored
View File

@@ -8,4 +8,7 @@ doc/_build/
gh-pages/
build/
dist/
.vscode/
.vscode/
/__pycache__/
/pyalsaaudio.egg-info/
*.raw

99
CHANGES
View File

@@ -1,99 +0,0 @@
Version 0.8.6:
- Added four methods to the 'PCM' class to allow users to get detailed information about the device:
- 'getformats()' returns a dictionary of name / value pairs, one for each of the card's
supported formats - e.g. '{"U8": 1, "S16_LE": 2}',
- 'getchannels()' returns a list of the supported channel numbers, e.g. '[1, 2]',
- 'getrates()' returns supported sample rates for the device, e.g. '[48000]',
- 'getratebounds()' returns the device's official minimum and maximum supported
sample rates as a tuple, e.g. '(4000, 48000)'.
(#82 contributed by @jdstmporter)
- Prevent hang on close after capturing audio (#80 contributed by @daym)
Version 0.8.5:
- Return an empty string/bytestring when 'read()' detects an
overrun. Previously the returned data was undefined (contributed by @jcea)
- Unlimited setperiod buffer size when reading frames (contributed by @jcea)
Version 0.8.4:
- Fix Python3 API usage broken in 0.8.3
Version 0.8.3:
- Add DSD sample formats (contributed by @lintweaker)
- Add Mixer.handleevents() to acknowledge events identified by select.poll (contributed by @PaulSD)
- Add functions for listing cards and their names (contributed by @chrisdiamand)
- Add a method for setting enums (contributed by @chrisdiamand)
Version 0.8.2:
- fix #3 (we cannot get the revision from git for pip installs)
Version 0.8.1:
- document changes (this file)
Version 0.8:
- 'PCM()' has new 'device' and 'cardindex' keyword arguments.
The keyword 'device' allows to select virtual devices, 'cardindex' can be
used to select hardware cards by index (as with 'mixers()' and 'Mixer()').
The 'card' keyword argument is still supported, but deprecated.
The reason for this change is that the 'card' keyword argument guessed
a device name from the card name, but this only works sometimes, and breaks
opening virtual devices.
- new function 'pcms()' to list available PCM devices.
- mixers() and Mixer() take an additional 'device' keyword argument.
This allows to list or open virtual devices.
- The default behaviour of Mixer() without any arguments has changed.
Now Mixer() will try to open the 'default' Mixer instead of the Mixer
that is associated with card 0.
- fix a memory leak under Python 3.x
- some more memory leaks in error conditions fixed.
Version 0.7:
- fixed several memory leaks (patch 3372909), contributed by Erik Kulyk)
Version 0.6:
- mostly reverted patch 2594366: alsapcm_setup did not do complete error
checking for good reasons; some ALSA functions in alsapcm_setup may fail without
rendering the device unusable
Version 0.5:
- applied patch 2777035: Fixed setrec method in alsaaudio.c
This included a mixertest with more features
- fixed/applied patch 2594366: alsapcm_setup does not do any error checking
Version 0.4:
- API changes: mixers() and Mixer() now take a card index instead of a
card name as optional parameter.
- Support for Python 3.0
- Documentation converted to reStructuredText; use Sphinx instead of LaTeX.
- added cards()
- added PCM.close()
- added Mixer.close()
- added mixer.getenum()
Version 0.3:
- wrapped blocking calls with Py_BEGIN_ALLOW_THREADS/Py_END_ALLOW_THREADS
- added pause
Version 0.2:
- Many bugfixes related to playback in particular
- Module documentation in the doc subdirectory
Version 0.1:
- Initial version

112
CHANGES.md Normal file
View File

@@ -0,0 +1,112 @@
# Version 0.10.0
- assorted improvements (#123 from @ossilator)
- support for `periods` in the `PCM` constructor.
- new functions `PCM.state()`, `PCM.drop()` and `PCM.drain()`
- improved underrun/overrun handling
- documentation improvements/consolidation (docstrings were removed in favour of online documentation)
- more sampling rates
- bug fixes
# Version 0.9.2
- Fix alsamixer_getvolume (#112 from @stephensp)
# Version 0.9.1:
- Support decibel, percentage, and raw volumes in getvolume, setvolume, and getrange (#109 from @chrisdiamand)
# Version 0.9.0:
- Added keyword arguments for channels, format, rate and periodsize
- Deprecated `setchannel`, `setformat`, `setrate` and `setperiodsize`
# Version 0.8.6:
- Added four methods to the `PCM` class to allow users to get detailed information about the device:
- `getformats()` returns a dictionary of name / value pairs, one for each of the card's
supported formats - e.g. `{"U8": 1, "S16_LE": 2}`,
- `getchannels()` returns a list of the supported channel numbers, e.g. `[1, 2]`,
- `getrates()` returns supported sample rates for the device, e.g. `[48000]`,
- `getratebounds()` returns the device's official minimum and maximum supported
sample rates as a tuple, e.g. `(4000, 48000)`.
(#82 contributed by @jdstmporter)
- Prevent hang on close after capturing audio (#80 contributed by @daym)
# Version 0.8.5:
- Return an empty string/bytestring when `read()` detects an
overrun. Previously the returned data was undefined (contributed by @jcea)
- Unlimited setperiod buffer size when reading frames (contributed by @jcea)
# Version 0.8.4:
- Fix Python3 API usage broken in 0.8.3
# Version 0.8.3:
- Add DSD sample formats (contributed by @lintweaker)
- Add Mixer.handleevents() to acknowledge events identified by select.poll (contributed by @PaulSD)
- Add functions for listing cards and their names (contributed by @chrisdiamand)
- Add a method for setting enums (contributed by @chrisdiamand)
# Version 0.8.2:
- fix #3 (we cannot get the revision from git for pip installs)
# Version 0.8.1:
- document changes (this file)
# Version 0.8:
- `PCM()` has new `device` and `cardindex` keyword arguments.
The keyword `device` allows to select virtual devices, `cardindex` can be
used to select hardware cards by index (as with `mixers()` and `Mixer()`).
The `card` keyword argument is still supported, but deprecated.
The reason for this change is that the `card` keyword argument guessed
a device name from the card name, but this only works sometimes, and breaks
opening virtual devices.
- new function `pcms()` to list available PCM devices.
- `mixers()` and `Mixer()` take an additional `device` keyword argument.
This allows to list or open virtual devices.
- The default behaviour of `Mixer()` without any arguments has changed.
Now Mixer() will try to open the `default` Mixer instead of the Mixer
that is associated with card 0.
- fix a memory leak under Python 3.x
- some more memory leaks in error conditions fixed.
# Version 0.7:
- fixed several memory leaks (patch 3372909), contributed by Erik Kulyk)
# Version 0.6:
- mostly reverted patch 2594366: alsapcm_setup did not do complete error
checking for good reasons; some ALSA functions in alsapcm_setup may fail without
rendering the device unusable
# Version 0.5:
- applied patch 2777035: Fixed setrec method in alsaaudio.c
This included a mixertest with more features
- fixed/applied patch 2594366: alsapcm_setup does not do any error checking
# Version 0.4:
- API changes: mixers() and Mixer() now take a card index instead of a
card name as optional parameter.
- Support for Python 3.0
- Documentation converted to reStructuredText; use Sphinx instead of LaTeX.
- added `cards()`
- added `PCM.close()`
- added `Mixer.close()`
- added `mixer.getenum()`
# Version 0.3:
- wrapped blocking calls with `Py_BEGIN_ALLOW_THREADS`/`Py_END_ALLOW_THREADS`
- added pause
# Version 0.2:
- Many bugfixes related to playback in particular
- Module documentation in the doc subdirectory
# Version 0.1:
- Initial version

View File

@@ -1,11 +0,0 @@
# Publishing the documentation
- Install Sphinx; `sudo pip install sphinx`
- Clone gh-pages branch: `cd doc; git clone -b gh-pages git@github.com:larsimmisch/pyalsaaudio.git gh-pages`
- `cd doc; make publish`
# Release procedure
- Update version number in setup.py
- Create tag and push it, i.e. `git tag x.y.z; git push origin x.y.z`
- `python setup.py sdist upload -r pypi`

File diff suppressed because it is too large Load Diff

View File

@@ -11,10 +11,14 @@ Create and push a tag naming the version (i.e. 0.9.0):
git tag 0.9.0
git push origin 0.9.0
Upload the package:
Create the package:
python3 setup.py sdist
Upload the package
twine upload dist/*
Don't forget to update the documentation.
# Publish the documentation

View File

@@ -1,8 +1,3 @@
.. alsaaudio documentation documentation master file, created by
sphinx-quickstart on Thu Mar 30 23:52:21 2017.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
alsaaudio documentation
===================================================
@@ -18,15 +13,13 @@ Download
========
* `Download from pypi <https://pypi.python.org/pypi/pyalsaaudio>`_
Github
======
* `Repository <https://github.com/larsimmisch/pyalsaaudio/>`_
* `Bug tracker <https://github.com/larsimmisch/pyalsaaudio/issues>`_
Indices and tables
==================
@@ -34,5 +27,3 @@ Indices and tables
* :ref:`modindex`
* :ref:`search`

View File

@@ -5,41 +5,18 @@
.. module:: alsaaudio
:platform: Linux
.. % \declaremodule{builtin}{alsaaudio} % standard library, in C
.. % not standard, in C
.. moduleauthor:: Casper Wilstrup <cwi@aves.dk>
.. moduleauthor:: Lars Immisch <lars@ibp.de>
.. % Author of the module code;
The :mod:`alsaaudio` module defines functions and classes for using ALSA.
.. % ---- 3.1. ----
.. % For each function, use a ``funcdesc'' block. This has exactly two
.. % parameters (each parameters is contained in a set of curly braces):
.. % the first parameter is the function name (this automatically
.. % generates an index entry); the second parameter is the function's
.. % argument list. If there are no arguments, use an empty pair of
.. % curly braces. If there is more than one argument, separate the
.. % arguments with backslash-comma. Optional parts of the parameter
.. % list are contained in \optional{...} (this generates a set of square
.. % brackets around its parameter). Arguments are automatically set in
.. % italics in the parameter list. Each argument should be mentioned at
.. % least once in the description; each usage (even inside \code{...})
.. % should be enclosed in \var{...}.
.. function:: pcms([type=PCM_PLAYBACK])
.. function:: pcms(pcmtype=PCM_PLAYBACK)
List available PCM devices by name.
Arguments are:
* *type* - can be either :const:`PCM_CAPTURE` or :const:`PCM_PLAYBACK`
* *pcmtype* - can be either :const:`PCM_CAPTURE` or :const:`PCM_PLAYBACK`
(default).
**Note:**
@@ -62,7 +39,13 @@ The :mod:`alsaaudio` module defines functions and classes for using ALSA.
List the available ALSA cards by name. This function is only moderately
useful. If you want to see a list of available PCM devices, use :func:`pcms`
instead.
..
Omitted by intention due to being superseded by cards():
.. function:: card_indexes()
.. function:: card_name()
.. function:: mixers(cardindex=-1, device='default')
List the available mixers. The arguments are:
@@ -72,12 +55,14 @@ The :mod:`alsaaudio` module defines functions and classes for using ALSA.
the `device` keyword argument is ignored. ``0`` is the first hardware sound
card.
**Note:** This should not be used, as it bypasses most of ALSA's configuration.
* *device* - the name of the device on which the mixer resides. The default
is ``'default'``.
**Note:** For a list of available controls, you can also use ``amixer`` on
the commandline::
$ amixer
To elaborate the example, calling :func:`mixers` with the argument
@@ -91,12 +76,16 @@ The :mod:`alsaaudio` module defines functions and classes for using ALSA.
$ amixer -D foo
*Changed in 0.8*:
- The keyword argument `device` is new and can be used to
select virtual devices. As a result, the default behaviour has subtly
changed. Since 0.8, this functions returns the mixers for the default
device, not the mixers for the first card.
.. function:: asoundlib_version()
Return a Python string containing the ALSA version found.
.. _pcm-objects:
@@ -107,7 +96,7 @@ PCM objects in :mod:`alsaaudio` can play or capture (record) PCM
sound through speakers or a microphone. The PCM constructor takes the
following arguments:
.. class:: PCM(type=PCM_PLAYBACK, mode=PCM_NORMAL, rate=44100, channels=2, format=PCM_FORMAT_S16_LE, periodsize=32, device='default', cardindex=-1)
.. class:: PCM(type=PCM_PLAYBACK, mode=PCM_NORMAL, rate=44100, channels=2, format=PCM_FORMAT_S16_LE, periodsize=32, periods=4, device='default', cardindex=-1)
This class is used to represent a PCM device (either for playback and
recording). The arguments are:
@@ -116,17 +105,16 @@ following arguments:
(default).
* *mode* - can be either :const:`PCM_NONBLOCK`, or :const:`PCM_NORMAL`
(default).
* *rate* - the sampling rate in Hz. Typical values are ``8000``
(mainly used for telephony), ``16000``, ``44100`` (default), ``48000`` and ``96000``.
* *rate* - the sampling rate in Hz. Typical values are ``8000`` (mainly used for telephony), ``16000``, ``44100`` (default), ``48000`` and ``96000``.
* *channels* - the number of channels. The default value is 2 (stereo).
* *format* - the data format. This controls how the PCM device interprets data for playback, and how data is encoded in captures.
The default value is :const:`PCM_FORMAT_S16_LE`.
========================= ===============
Format Description
========================= ===============
``PCM_FORMAT_S8`` Signed 8 bit samples for each channel
``PCM_FORMAT_U8`` Signed 8 bit samples for each channel
``PCM_FORMAT_U8`` Unsigned 8 bit samples for each channel
``PCM_FORMAT_S16_LE`` Signed 16 bit samples for each channel Little Endian byte order)
``PCM_FORMAT_S16_BE`` Signed 16 bit samples for each channel (Big Endian byte order)
``PCM_FORMAT_U16_LE`` Unsigned 16 bit samples for each channel (Little Endian byte order)
@@ -154,7 +142,11 @@ following arguments:
``PCM_FORMAT_U24_3BE`` Unsigned 24 bit samples for each channel (Big Endian byte order in 3 bytes)
========================= ===============
* *periodsize* - the period size in frames. Each write should consist of *periodsize* frames. The default value is 32.
* *periodsize* - the period size in frames.
Make sure you understand :ref:`the meaning of periods <term-period>`.
The default value is 32, which is below the actual minimum of most devices,
and will therefore likely be larger in practice.
* *periods* - the number of periods in the buffer. The default value is 4.
* *device* - the name of the PCM device that should be used (for example
a value from the output of :func:`pcms`). The default value is
``'default'``.
@@ -163,14 +155,20 @@ following arguments:
the `device` keyword argument is ignored.
``0`` is the first hardware sound card.
**Note:** This should not be used, as it bypasses most of ALSA's configuration.
This will construct a PCM object with the given settings.
*Changed in 0.10:*
- Added the optional named parameter `periods`.
*Changed in 0.9:*
- Added the optional named parameters `rate`, `channels`, `format` and `periodsize`.
*Changed in 0.8:*
- The `card` keyword argument is still supported,
but deprecated. Please use `device` instead.
@@ -178,26 +176,97 @@ following arguments:
The `card` keyword is deprecated because it guesses the real ALSA
name of the card. This was always fragile and broke some legitimate usecases.
PCM objects have the following methods:
.. method:: PCM.info()
The info function returns a dictionary containing the configuration of a PCM device. As ALSA takes into account limitations of the hardware and software devices the configuration achieved might not correspond to the values used during creation. There is therefore a need to check the realised configuration before processing the sound coming from the device or before sending sound to a device. A small subset of parameters can be set, but cannot be queried. These parameters are stored by alsaaudio and returned as they were given by the user, to distinguish them from parameters retrieved from ALSA these parameters have a name prefixed with **" (call value) "**. Yet another set of properties derives directly from the hardware and can be obtained through ALSA.
=========================== ============================= ==================================================================
Key Description (Reference) Type
=========================== ============================= ==================================================================
name PCM():device string
card_no *index of card* integer (negative indicates device not associable with a card)
device_no *index of PCM device* integer
subdevice_no *index of PCM subdevice* integer
state *name of PCM state* string
access_type *name of PCM access type* string
(call value) type PCM():type integer
(call value) type_name PCM():type string
(call value) mode PCM():mode integer
(call value) mode_name PCM():mode string
format PCM():format integer
format_name PCM():format string
format_description PCM():format string
subformat_name *name of PCM subformat* string
subformat_description *description of subformat* string
channels PCM():channels integer
rate PCM():rate integer (Hz)
period_time *period duration* integer (:math:`\mu s`)
period_size PCM():period_size integer (frames)
buffer_time *buffer time* integer (:math:`\mu s`) (negative indicates error)
buffer_size *buffer size* integer (frames) (negative indicates error)
get_periods *approx. periods in buffer* integer (negative indicates error)
rate_numden *numerator, denominator* tuple (integer (Hz), integer (Hz))
significant_bits *significant bits in sample* integer (negative indicates error)
is_batch *hw: double buffering* boolean (True: hardware supported)
is_block_transfer *hw: block transfer* boolean (True: hardware supported)
is_double *hw: double buffering* boolean (True: hardware supported)
is_half_duplex *hw: half-duplex* boolean (True: hardware supported)
is_joint_duplex *hw: joint-duplex* boolean (True: hardware supported)
can_overrange *hw: overrange detection* boolean (True: hardware supported)
can_mmap_sample_resolution *hw: sample-resol. mmap* boolean (True: hardware supported)
can_pause *hw: pause* boolean (True: hardware supported)
can_resume *hw: resume* boolean (True: hardware supported)
can_sync_start *hw: synchronized start* boolean (True: hardware supported)
=========================== ============================= ==================================================================
The italicized descriptions give a summary of the "full" description as it can be found in the `ALSA documentation <https://www.alsa-project.org/alsa-doc>`_. "hw:": indicates that the property indicated relates to the hardware. Parameters passed to the PCM object during instantation are prefixed with "PCM():", they are described there for the keyword argument indicated after "PCM():".
.. method:: PCM.pcmtype()
Returns the type of PCM object. Either :const:`PCM_CAPTURE` or
:const:`PCM_PLAYBACK`.
.. method:: PCM.pcmmode()
Return the mode of the PCM object. One of :const:`PCM_NONBLOCK`,
:const:`PCM_ASYNC`, or :const:`PCM_NORMAL`
.. method:: PCM.cardname()
Return the name of the sound card used by this PCM object.
..
Omitted by intention due to not really fitting the c'tor-based setup concept:
.. method:: PCM.getchannels()
Returns list of the device's supported channel counts.
.. method:: PCM.getratebounds()
Returns the card's minimum and maximum supported sample rates as
a tuple of integers.
.. method:: PCM.getrates()
Returns the sample rates supported by the device.
The returned value can be of one of the following, depending on
the card's properties:
* Card supports only a single rate: returns the rate
* Card supports a continuous range of rates: returns a tuple of
the range's lower and upper bounds (inclusive)
* Card supports a collection of well-known rates: returns a list of
the supported rates
.. method:: PCM.getformats()
Returns a dictionary of supported format codes (integers) keyed by
their standard ALSA names (strings).
.. method:: PCM.setchannels(nchannels)
.. deprecated:: 0.9 Use the `channels` named argument to :func:`PCM`.
@@ -207,13 +276,42 @@ PCM objects have the following methods:
.. deprecated:: 0.9 Use the `rate` named argument to :func:`PCM`.
.. method:: PCM.setformat(format)
.. deprecated:: 0.9 Use the `format` named argument to :func:`PCM`.
.. method:: PCM.setperiodsize(period)
.. deprecated:: 0.9 Use the `periodsize` named argument to :func:`PCM`.
.. method:: PCM.info()
Returns a dictionary with the PCM object's configured parameters.
Values are retrieved from the ALSA library if they are available;
otherwise they represent those stored by pyalsaaudio, and their keys
are prefixed with ' (call value) '.
*New in 0.9.1*
.. method:: PCM.dumpinfo()
Dumps the PCM object's configured parameters to stdout.
.. method:: PCM.state()
Returs the current state of the stream, which can be one of
:const:`PCM_STATE_OPEN` (this should not actually happen),
:const:`PCM_STATE_SETUP` (after :func:`drop` or :func:`drain`),
:const:`PCM_STATE_PREPARED` (after construction),
:const:`PCM_STATE_RUNNING`,
:const:`PCM_STATE_XRUN`,
:const:`PCM_STATE_DRAINING`,
:const:`PCM_STATE_PAUSED`,
:const:`PCM_STATE_SUSPENDED`, and
:const:`PCM_STATE_DISCONNECTED`.
*New in 0.10*
.. method:: PCM.read()
In :const:`PCM_NORMAL` mode, this function blocks until a full period is
@@ -246,22 +344,94 @@ PCM objects have the following methods:
return value of zero, if the buffer is full. In this case, the data
should be written at a later time.
Note that this call completing means only that the samples were buffered
in the kernel, and playout will continue afterwards. Make sure that the
stream is drained before discarding the PCM handle.
.. method:: PCM.pause([enable=True])
If *enable* is :const:`True`, playback or capture is paused.
Otherwise, playback/capture is resumed.
.. method:: PCM.drop()
Stop the stream and drop residual buffered frames.
*New in 0.9*
.. method:: PCM.drain()
For :const:`PCM_PLAYBACK` PCM objects, play residual buffered frames
and then stop the stream. In :const:`PCM_NORMAL` mode,
this function blocks until all pending playback is drained.
For :const:`PCM_CAPTURE` PCM objects, this function is not very useful.
*New in 0.10*
.. method:: PCM.close()
Closes the PCM device.
For :const:`PCM_PLAYBACK` PCM objects in :const:`PCM_NORMAL` mode,
this function blocks until all pending playback is drained.
.. method:: PCM.polldescriptors()
Returns a tuple of *(file descriptor, eventmask)* that can be used to
wait for changes on the mixer with *select.poll*.
Returns a list of tuples of *(file descriptor, eventmask)* that can be
used to wait for changes on the PCM with *select.poll*.
The *eventmask* value is compatible with `poll.register`__ in the Python
:const:`select` module.
__ poll_objects_
.. method:: PCM.set_tstamp_mode([mode=PCM_TSTAMP_ENABLE])
Set the ALSA timestamp mode on the device. The mode argument can be set to
either :const:`PCM_TSTAMP_NONE` or :const:`PCM_TSTAMP_ENABLE`.
.. method:: PCM.get_tstamp_mode()
Return the integer value corresponding to the ALSA timestamp mode. The
return value can be either :const:`PCM_TSTAMP_NONE` or :const:`PCM_TSTAMP_ENABLE`.
.. method:: PCM.set_tstamp_type([type=PCM_TSTAMP_TYPE_GETTIMEOFDAY])
Set the ALSA timestamp mode on the device. The type argument
can be set to either :const:`PCM_TSTAMP_TYPE_GETTIMEOFDAY`,
:const:`PCM_TSTAMP_TYPE_MONOTONIC` or :const:`PCM_TSTAMP_TYPE_MONOTONIC_RAW`.
.. method:: PCM.get_tstamp_type()
Return the integer value corresponding to the ALSA timestamp type. The
return value can be either :const:`PCM_TSTAMP_TYPE_GETTIMEOFDAY`,
:const:`PCM_TSTAMP_TYPE_MONOTONIC` or :const:`PCM_TSTAMP_TYPE_MONOTONIC_RAW`.
.. method:: PCM.htimestamp()
Return a Python tuple *(seconds, nanoseconds, frames_available_in_buffer)*.
The type of output is controlled by the tstamp_type, as described in the table below.
================================= ===========================================
Timestamp Type Description
================================= ===========================================
``PCM_TSTAMP_TYPE_GETTIMEOFDAY`` System-wide realtime clock with seconds
since epoch.
``PCM_TSTAMP_TYPE_MONOTONIC`` Monotonic time from an unspecified starting
time. Progress is NTP synchronized.
``PCM_TSTAMP_TYPE_MONOTONIC_RAW`` Monotonic time from an unspecified starting
time using only the system clock.
================================= ===========================================
The timestamp mode is controlled by the tstamp_mode, as described in the table below.
================================= ===========================================
Timestamp Mode Description
================================= ===========================================
``PCM_TSTAMP_NONE`` No timestamp.
``PCM_TSTAMP_ENABLE`` Update timestamp at every hardware position
update.
================================= ===========================================
**A few hints on using PCM devices for playback**
@@ -298,11 +468,10 @@ Mixer Objects
Mixer objects provides access to the ALSA mixer API.
.. class:: Mixer(control='Master', id=0, cardindex=-1, device='default')
Arguments are:
* *control* - specifies which control to manipulate using this mixer
object. The list of available controls can be found with the
:mod:`alsaaudio`.\ :func:`mixers` function. The default value is
@@ -318,30 +487,27 @@ Mixer objects provides access to the ALSA mixer API.
* *device* - the name of the device on which the mixer resides. The default
value is ``'default'``.
*Changed in 0.8*:
- The keyword argument `device` is new and can be used to select virtual
devices.
Mixer objects have the following methods:
.. method:: Mixer.cardname()
Return the name of the sound card used by this Mixer object
.. method:: Mixer.mixer()
Return the name of the specific mixer controlled by this object, For example
``'Master'`` or ``'PCM'``
.. method:: Mixer.mixerid()
Return the ID of the ALSA mixer controlled by this object.
.. method:: Mixer.switchcap()
Returns a list of the switches which are defined by this specific mixer.
@@ -362,7 +528,6 @@ Mixer objects have the following methods:
To manipulate these switches use the :meth:`setrec` or
:meth:`setmute` methods
.. method:: Mixer.volumecap()
Returns a list of the volume control capabilities of this
@@ -378,7 +543,7 @@ Mixer objects have the following methods:
'Capture Volume' Manipulate sound capture volume
'Joined Capture Volume' Manipulate sound capture volume for all channels at a time
======================== ================
.. method:: Mixer.getenum()
For enumerated controls, return the currently selected item and the list of
@@ -405,58 +570,63 @@ Mixer objects have the following methods:
This method will return an empty tuple if the mixer is not an enumerated
control.
.. method:: Mixer.setenum(index)
.. method:: Mixer.getmute()
For enumerated controls, sets the currently selected item.
*index* is an index into the list of available enumerated items returned
by :func:`getenum`.
Return a list indicating the current mute setting for each
channel. 0 means not muted, 1 means muted.
This method will fail if the mixer has no playback switch capabilities.
.. method:: Mixer.getrange([direction])
.. method:: Mixer.getrange(pcmtype=PCM_PLAYBACK, units=VOLUME_UNITS_RAW)
Return the volume range of the ALSA mixer controlled by this object.
The value is a tuple of integers whose meaning is determined by the
*units* argument.
The optional *direction* argument can be either :const:`PCM_PLAYBACK` or
The optional *pcmtype* argument can be either :const:`PCM_PLAYBACK` or
:const:`PCM_CAPTURE`, which is relevant if the mixer can control both
playback and capture volume. The default value is :const:`PCM_PLAYBACK`
if the mixer has playback channels, otherwise it is :const:`PCM_CAPTURE`.
The optional *units* argument can be one of :const:`VOLUME_UNITS_PERCENTAGE`,
:const:`VOLUME_UNITS_RAW`, or :const:`VOLUME_UNITS_DB`.
.. method:: Mixer.getrec()
Return a list indicating the current record mute setting for each channel. 0
means not recording, 1 means recording.
This method will fail if the mixer has no capture switch capabilities.
.. method:: Mixer.getvolume([direction])
.. method:: Mixer.getvolume(pcmtype=PCM_PLAYBACK, units=VOLUME_UNITS_PERCENTAGE)
Returns a list with the current volume settings for each channel. The list
elements are integer percentages.
elements are integers whose meaning is determined by the *units* argument.
The optional *direction* argument can be either :const:`PCM_PLAYBACK` or
The optional *pcmtype* argument can be either :const:`PCM_PLAYBACK` or
:const:`PCM_CAPTURE`, which is relevant if the mixer can control both
playback and capture volume. The default value is :const:`PCM_PLAYBACK`
if the mixer has playback channels, otherwise it is :const:`PCM_CAPTURE`.
The optional *units* argument can be one of :const:`VOLUME_UNITS_PERCENTAGE`,
:const:`VOLUME_UNITS_RAW`, or :const:`VOLUME_UNITS_DB`.
.. method:: Mixer.setvolume(volume, [channel], [direction])
.. method:: Mixer.setvolume(volume, channel=None, pcmtype=PCM_PLAYBACK, units=VOLUME_UNITS_PERCENTAGE)
Change the current volume settings for this mixer. The *volume* argument
controls the new volume setting as an integer percentage.
is an integer whose meaning is determined by the *units* argument.
If the optional argument *channel* is present, the volume is set
only for this channel. This assumes that the mixer can control the
volume for the channels independently.
The optional *direction* argument can be either :const:`PCM_PLAYBACK` or
The optional *pcmtype* argument can be either :const:`PCM_PLAYBACK` or
:const:`PCM_CAPTURE`, which is relevant if the mixer can control both
playback and capture volume. The default value is :const:`PCM_PLAYBACK`
if the mixer has playback channels, otherwise it is :const:`PCM_CAPTURE`.
The optional *units* argument can be one of :const:`VOLUME_UNITS_PERCENTAGE`,
:const:`VOLUME_UNITS_RAW`, or :const:`VOLUME_UNITS_DB`.
.. method:: Mixer.getmute()
Return a list indicating the current mute setting for each channel.
0 means not muted, 1 means muted.
This method will fail if the mixer has no playback switch capabilities.
.. method:: Mixer.setmute(mute, [channel])
Sets the mute flag to a new value. The *mute* argument is either 0 for not
@@ -467,6 +637,12 @@ Mixer objects have the following methods:
This method will fail if the mixer has no playback mute capabilities
.. method:: Mixer.getrec()
Return a list indicating the current record mute setting for each channel.
0 means not recording, 1 means recording.
This method will fail if the mixer has no capture switch capabilities.
.. method:: Mixer.setrec(capture, [channel])
@@ -480,20 +656,22 @@ Mixer objects have the following methods:
.. method:: Mixer.polldescriptors()
Returns a tuple of *(file descriptor, eventmask)* that can be used to
wait for changes on the mixer with *select.poll*.
Returns a list of tuples of *(file descriptor, eventmask)* that can be
used to wait for changes on the mixer with *select.poll*.
The *eventmask* value is compatible with `poll.register`__ in the Python
:const:`select` module.
__ poll_objects_
.. method:: Mixer.handleevents()
Acknowledge events on the *polldescriptors* file descriptors
Acknowledge events on the :func:`polldescriptors` file descriptors
to prevent subsequent polls from returning the same events again.
Returns the number of events that were acknowledged.
.. method:: Mixer.close()
Closes the Mixer device.
**A rant on the ALSA Mixer API**
The ALSA mixer API is extremely complicated - and hardly documented at all.
@@ -516,8 +694,6 @@ Unfortunately, I'm not able to create such a HOWTO myself, since I only
understand half of the API, and that which I do understand has come from a
painful trial and error process.
.. % ==== 4. ====
.. _pcm-example:
@@ -559,6 +735,7 @@ To test PCM playback (on your default soundcard), run::
recordtest.py and playbacktest.py
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
**recordtest.py** and **playbacktest.py** will record and play a raw
sound file in CD quality.
@@ -580,7 +757,7 @@ Without arguments, **mixertest.py** will list all available *controls* on the
default soundcard.
The output might look like this::
$ ./mixertest.py
Available mixer controls:
'Master'
@@ -628,9 +805,3 @@ argument::
Capabilities: Playback Volume Playback Mute
Channel 0 volume: 61%
Channel 1 volume: 61%
.. rubric:: Footnotes
.. [#f1] ALSA also allows ``PCM_ASYNC``, but this is not supported yet.
.. _poll_objects: http://docs.python.org/library/select.html#poll-objects

View File

@@ -7,33 +7,19 @@ Introduction
.. |release| replace:: version
.. % At minimum, give your name and an email address. You can include a
.. % snail-mail address if you like.
.. % This makes the Abstract go on a separate page in the HTML version;
.. % if a copyright notice is used, it should go immediately after this.
.. %
.. _front:
This software is licensed under the PSF license - the same one used by the
majority of the python distribution. Basically you can use it for anything you
wish (even commercial purposes). There is no warranty whatsoever.
.. % Copyright statement should go here, if needed.
.. % The abstract should be a paragraph or two long, and describe the
.. % scope of the document.
.. topic:: Abstract
This package contains wrappers for accessing the ALSA API from Python. It is
currently fairly complete for PCM devices and Mixer access. MIDI sequencer
support is low on our priority list, but volunteers are welcome.
If you find bugs in the wrappers please use thegithub issue tracker.
If you find bugs in the wrappers please use the github issue tracker.
Please don't send bug reports regarding ALSA specifically. There are several
bugs in this API, and those should be reported to the ALSA team - not me.
@@ -64,8 +50,8 @@ More information about ALSA may be found on the project homepage
ALSA and Python
===============
The older Linux sound API (OSS) which is now deprecated is well supported from
the standard Python library, through the ossaudiodev module. No native ALSA
The older Linux sound API (OSS) -- which is now deprecated -- is well supported
by the standard Python library, through the ossaudiodev module. No native ALSA
support exists in the standard library.
There are a few other "ALSA for Python" projects available, including at least
@@ -106,6 +92,7 @@ And then as root: --- ::
# python setup.py install
*******
Testing
*******
@@ -130,7 +117,7 @@ with ``Ctl-C``.
Play back the recording with::
$ python playbacktest.py-d <device> <filename>
$ python playbacktest.py -d <device> <filename>
There is a minimal test suite in :code:`test.py`, but it is
a bit dependent on the ALSA configuration and may fail without indicating

View File

@@ -19,7 +19,7 @@ Sample
Musically, the sample size determines the dynamic range. The
dynamic range is the difference between the quietest and the
loudest signal that can be resproduced.
loudest signal that can be reproduced.
Frame
A frame consists of exactly one sample per channel. If there is only one
@@ -28,9 +28,9 @@ Frame
Frame size
This is the size in bytes of each frame. This can vary a lot: if each sample
is 8 bits, and we're handling mono sound, the frame size is one byte.
Similarly in 6 channel audio with 64 bit floating point samples, the frame
size is 48 bytes
is 8 bits, and we're handling mono sound, the frame size is one byte.
For six channel audio with 64 bit floating point samples, the frame size
is 48 bytes.
Rate
PCM sound consists of a flow of sound frames. The sound rate controls how
@@ -38,7 +38,7 @@ Rate
means that a new frame is played or captured 8000 times per second.
Data rate
This is the number of bytes, which must be recorded or provided per
This is the number of bytes which must be consumed or provided per
second at a certain frame size and rate.
8000 Hz mono sound with 8 bit (1 byte) samples has a data rate of
@@ -46,24 +46,40 @@ Data rate
At the other end of the scale, 96000 Hz, 6 channel sound with 64
bit (8 bytes) samples has a data rate of 96000 \* 6 \* 8 = 4608
kb/s (almost 5 MB sound data per second)
kb/s (almost 5 MB sound data per second).
If the data rate requirement is not met, an overrun (on capture) or
underrun (on playback) occurs; the term "xrun" is used to refer to
either event.
.. _term-period:
Period
When the hardware processes data this is done in chunks of frames. The time
interval between each processing (A/D or D/A conversion) is known
as the period.
The size of the period has direct implication on the latency of the
sound input or output. For low-latency the period size should be
very small, while low CPU resource usage would usually demand
larger period sizes. With ALSA, the CPU utilization is not impacted
much by the period size, since the kernel layer buffers multiple
periods internally, so each period generates an interrupt and a
memory copy, but userspace can be slower and read or write multiple
periods at the same time.
The CPU processes sample data in chunks of frames, so-called periods
(also called fragments by some systems). The operating system kernel's
sample buffer must hold at least two periods (at any given time, one
is processed by the sound hardware, and one by the CPU).
The completion of a *period* triggers a CPU interrupt, which causes
processing and context switching overhead. Therefore, a smaller period
size causes higher CPU resource usage at a given data rate.
A bigger size of the *buffer* improves the system's resilience to xruns.
The buffer being split into a bigger number of smaller periods also does
that, as it allows it to be drained / topped up sooner.
On the other hand, a bigger size of the *buffer* also increases the
playback latency, that is, the time it takes for a frame from being
sent out by the application to being actually audible.
Similarly, a bigger *period* size increases the capture latency.
The trade-off between latency, xrun resilience, and resource usage
must be made depending on the application.
Period size
This is the size of each period in Hz. *Not bytes, but Hz!.* In
:mod:`alsaaudio` the period size is set directly, and it is
This is the size of each period in frames. *Not bytes, but frames!*
In :mod:`alsaaudio` the period size is set directly, and it is
therefore important to understand the significance of this
number. If the period size is configured to for example 32,
each write should contain exactly 32 frames of sound data, and each

View File

@@ -43,11 +43,36 @@ def show_mixer(name, kwargs):
sys.exit(1)
print("Mixer name: '%s'" % mixer.mixer())
print("Capabilities: %s %s" % (' '.join(mixer.volumecap()),
volcap = mixer.volumecap()
print("Capabilities: %s %s" % (' '.join(volcap),
' '.join(mixer.switchcap())))
if "Volume" in volcap or "Joined Volume" in volcap or "Playback Volume" in volcap:
pmin, pmax = mixer.getrange(alsaaudio.PCM_PLAYBACK)
pmin_keyword, pmax_keyword = mixer.getrange(pcmtype=alsaaudio.PCM_PLAYBACK, units=alsaaudio.VOLUME_UNITS_RAW)
pmin_default, pmax_default = mixer.getrange()
assert pmin == pmin_keyword
assert pmax == pmax_keyword
assert pmin == pmin_default
assert pmax == pmax_default
print("Raw playback volume range {}-{}".format(pmin, pmax))
pmin_dB, pmax_dB = mixer.getrange(units=alsaaudio.VOLUME_UNITS_DB)
print("dB playback volume range {}-{}".format(pmin_dB / 100.0, pmax_dB / 100.0))
if "Capture Volume" in volcap or "Joined Capture Volume" in volcap:
# Check that `getrange` works with keyword and positional arguments
cmin, cmax = mixer.getrange(alsaaudio.PCM_CAPTURE)
cmin_keyword, cmax_keyword = mixer.getrange(pcmtype=alsaaudio.PCM_CAPTURE, units=alsaaudio.VOLUME_UNITS_RAW)
assert cmin == cmin_keyword
assert cmax == cmax_keyword
print("Raw capture volume range {}-{}".format(cmin, cmax))
cmin_dB, cmax_dB = mixer.getrange(pcmtype=alsaaudio.PCM_CAPTURE, units=alsaaudio.VOLUME_UNITS_DB)
print("dB capture volume range {}-{}".format(cmin_dB / 100.0, cmax_dB / 100.0))
volumes = mixer.getvolume()
volumes_dB = mixer.getvolume(units=alsaaudio.VOLUME_UNITS_DB)
for i in range(len(volumes)):
print("Channel %i volume: %i%%" % (i,volumes[i]))
print("Channel %i volume: %i%% (%.1f dB)" % (i, volumes[i], volumes_dB[i] / 100.0))
try:
mutes = mixer.getmute()

View File

@@ -49,5 +49,5 @@ if __name__ == '__main__':
while data:
out.write(data)
data = f.read(320)
out.close()

View File

@@ -58,7 +58,7 @@ if __name__ == '__main__':
loops -= 1
# Read data from device
l, data = inp.read()
if l:
f.write(data)
time.sleep(.001)

View File

@@ -8,7 +8,7 @@ from setuptools import setup
from setuptools.extension import Extension
from sys import version
pyalsa_version = '0.9.0'
pyalsa_version = '0.10.0'
if __name__ == '__main__':
setup(