Compare commits

..

1 Commits

Author SHA1 Message Date
Lars Immisch d3aa602a04 Setup PCM device in constructor. 2020-04-02 23:24:48 +02:00
17 changed files with 2497 additions and 3195 deletions
-5
View File
@@ -4,11 +4,6 @@ MANIFEST
doc/gh-pages/ doc/gh-pages/
doc/html/ doc/html/
doc/doctrees/ doc/doctrees/
doc/_build/
gh-pages/ gh-pages/
build/ build/
dist/ dist/
.vscode/
/__pycache__/
/pyalsaaudio.egg-info/
*.raw
+99
View File
@@ -0,0 +1,99 @@
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
View File
@@ -1,112 +0,0 @@
# 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
+11
View File
@@ -0,0 +1,11 @@
# 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`
+436 -917
View File
File diff suppressed because it is too large Load Diff
-23
View File
@@ -1,26 +1,3 @@
# Make a new release
Update the version in setup.py
pyalsa_version = '0.9.0'
Commit and push the update.
Create and push a tag naming the version (i.e. 0.9.0):
git tag 0.9.0
git push origin 0.9.0
Create the package:
python3 setup.py sdist
Upload the package
twine upload dist/*
Don't forget to update the documentation.
# Publish the documentation # Publish the documentation
The documentation is published through the `gh-pages` branch. The documentation is published through the `gh-pages` branch.
+9
View File
@@ -1,3 +1,8 @@
.. 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 alsaaudio documentation
=================================================== ===================================================
@@ -14,12 +19,14 @@ Download
* `Download from pypi <https://pypi.python.org/pypi/pyalsaaudio>`_ * `Download from pypi <https://pypi.python.org/pypi/pyalsaaudio>`_
Github Github
====== ======
* `Repository <https://github.com/larsimmisch/pyalsaaudio/>`_ * `Repository <https://github.com/larsimmisch/pyalsaaudio/>`_
* `Bug tracker <https://github.com/larsimmisch/pyalsaaudio/issues>`_ * `Bug tracker <https://github.com/larsimmisch/pyalsaaudio/issues>`_
Indices and tables Indices and tables
================== ==================
@@ -27,3 +34,5 @@ Indices and tables
* :ref:`modindex` * :ref:`modindex`
* :ref:`search` * :ref:`search`
+141 -301
View File
@@ -5,18 +5,41 @@
.. module:: alsaaudio .. module:: alsaaudio
:platform: Linux :platform: Linux
.. % \declaremodule{builtin}{alsaaudio} % standard library, in C
.. % not standard, in C
.. moduleauthor:: Casper Wilstrup <cwi@aves.dk> .. moduleauthor:: Casper Wilstrup <cwi@aves.dk>
.. moduleauthor:: Lars Immisch <lars@ibp.de> .. moduleauthor:: Lars Immisch <lars@ibp.de>
.. % Author of the module code;
The :mod:`alsaaudio` module defines functions and classes for using ALSA. The :mod:`alsaaudio` module defines functions and classes for using ALSA.
.. function:: pcms(pcmtype=PCM_PLAYBACK) .. % ---- 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])
List available PCM devices by name. List available PCM devices by name.
Arguments are: Arguments are:
* *pcmtype* - can be either :const:`PCM_CAPTURE` or :const:`PCM_PLAYBACK` * *type* - can be either :const:`PCM_CAPTURE` or :const:`PCM_PLAYBACK`
(default). (default).
**Note:** **Note:**
@@ -40,11 +63,6 @@ The :mod:`alsaaudio` module defines functions and classes for using ALSA.
useful. If you want to see a list of available PCM devices, use :func:`pcms` useful. If you want to see a list of available PCM devices, use :func:`pcms`
instead. instead.
..
Omitted by intention due to being superseded by cards():
.. function:: card_indexes()
.. function:: card_name()
.. function:: mixers(cardindex=-1, device='default') .. function:: mixers(cardindex=-1, device='default')
@@ -55,8 +73,6 @@ The :mod:`alsaaudio` module defines functions and classes for using ALSA.
the `device` keyword argument is ignored. ``0`` is the first hardware sound the `device` keyword argument is ignored. ``0`` is the first hardware sound
card. 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 * *device* - the name of the device on which the mixer resides. The default
is ``'default'``. is ``'default'``.
@@ -82,10 +98,6 @@ The :mod:`alsaaudio` module defines functions and classes for using ALSA.
changed. Since 0.8, this functions returns the mixers for the default changed. Since 0.8, this functions returns the mixers for the default
device, not the mixers for the first card. device, not the mixers for the first card.
.. function:: asoundlib_version()
Return a Python string containing the ALSA version found.
.. _pcm-objects: .. _pcm-objects:
@@ -96,7 +108,7 @@ PCM objects in :mod:`alsaaudio` can play or capture (record) PCM
sound through speakers or a microphone. The PCM constructor takes the sound through speakers or a microphone. The PCM constructor takes the
following arguments: following arguments:
.. 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) .. class:: PCM(type=PCM_PLAYBACK, mode=PCM_NORMAL, device='default', cardindex=-1)
This class is used to represent a PCM device (either for playback and This class is used to represent a PCM device (either for playback and
recording). The arguments are: recording). The arguments are:
@@ -105,16 +117,78 @@ following arguments:
(default). (default).
* *mode* - can be either :const:`PCM_NONBLOCK`, or :const:`PCM_NORMAL` * *mode* - can be either :const:`PCM_NONBLOCK`, or :const:`PCM_NORMAL`
(default). (default).
* *rate* - the sampling rate in Hz. Typical values are ``8000`` (mainly used for telephony), ``16000``, ``44100`` (default), ``48000`` and ``96000``. * *device* - the name of the PCM device that should be used (for example
* *channels* - the number of channels. The default value is 2 (stereo). a value from the output of :func:`pcms`). The default value is
* *format* - the data format. This controls how the PCM device interprets data for playback, and how data is encoded in captures. ``'default'``.
The default value is :const:`PCM_FORMAT_S16_LE`. * *cardindex* - the card index. If this argument is given, the device name
is constructed as 'hw:*cardindex*' and
the `device` keyword argument is ignored.
``0`` is the first hardware sound card.
This will construct a PCM object with these default settings:
* Sample format: :const:`PCM_FORMAT_S16_LE`
* Rate: 44100 Hz
* Channels: 2
* Period size: 32 frames
*Changed in 0.8:*
- The `card` keyword argument is still supported,
but deprecated. Please use `device` instead.
- The keyword argument `cardindex` was added.
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.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.
.. method:: PCM.setchannels(nchannels)
Used to set the number of capture or playback channels. Common
values are: ``1`` = mono, ``2`` = stereo, and ``6`` = full 6 channel audio.
Few sound cards support more than 2 channels
.. method:: PCM.setrate(rate)
Set the sample rate in Hz for the device. Typical values are ``8000``
(mainly used for telephony), ``16000``, ``44100`` (CD quality),
``48000`` and ``96000``.
.. method:: PCM.setformat(format)
The sound *format* of the device. Sound format controls how the PCM device
interpret data for playback, and how data is encoded in captures.
The following formats are provided by ALSA:
========================= =============== ========================= ===============
Format Description Format Description
========================= =============== ========================= ===============
``PCM_FORMAT_S8`` Signed 8 bit samples for each channel ``PCM_FORMAT_S8`` Signed 8 bit samples for each channel
``PCM_FORMAT_U8`` Unsigned 8 bit samples for each channel ``PCM_FORMAT_U8`` Signed 8 bit samples for each channel
``PCM_FORMAT_S16_LE`` Signed 16 bit samples for each channel Little Endian byte order) ``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_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) ``PCM_FORMAT_U16_LE`` Unsigned 16 bit samples for each channel (Little Endian byte order)
@@ -142,175 +216,14 @@ following arguments:
``PCM_FORMAT_U24_3BE`` Unsigned 24 bit samples for each channel (Big Endian byte order in 3 bytes) ``PCM_FORMAT_U24_3BE`` Unsigned 24 bit samples for each channel (Big Endian byte order in 3 bytes)
========================= =============== ========================= ===============
* *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'``.
* *cardindex* - the card index. If this argument is given, the device name
is constructed as 'hw:*cardindex*' and
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.
- The keyword argument `cardindex` was added.
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`.
.. method:: PCM.setrate(rate)
.. 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) .. method:: PCM.setperiodsize(period)
.. deprecated:: 0.9 Use the `periodsize` named argument to :func:`PCM`. Sets the actual period size in frames. Each write should consist of
exactly this number of frames, and each read will return this
number of frames (unless the device is in :const:`PCM_NONBLOCK` mode, in
which case it may return nothing at all)
.. 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() .. method:: PCM.read()
@@ -344,94 +257,22 @@ PCM objects have the following methods:
return value of zero, if the buffer is full. In this case, the data return value of zero, if the buffer is full. In this case, the data
should be written at a later time. 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]) .. method:: PCM.pause([enable=True])
If *enable* is :const:`True`, playback or capture is paused. If *enable* is :const:`True`, playback or capture is paused.
Otherwise, playback/capture is resumed. 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() .. method:: PCM.polldescriptors()
Returns a list of tuples of *(file descriptor, eventmask)* that can be Returns a tuple of *(file descriptor, eventmask)* that can be used to
used to wait for changes on the PCM with *select.poll*. wait for changes on the mixer with *select.poll*.
The *eventmask* value is compatible with `poll.register`__ in the Python The *eventmask* value is compatible with `poll.register`__ in the Python
:const:`select` module. :const:`select` module.
.. method:: PCM.set_tstamp_mode([mode=PCM_TSTAMP_ENABLE]) __ poll_objects_
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** **A few hints on using PCM devices for playback**
@@ -468,6 +309,7 @@ Mixer Objects
Mixer objects provides access to the ALSA mixer API. Mixer objects provides access to the ALSA mixer API.
.. class:: Mixer(control='Master', id=0, cardindex=-1, device='default') .. class:: Mixer(control='Master', id=0, cardindex=-1, device='default')
Arguments are: Arguments are:
@@ -499,15 +341,18 @@ Mixer objects have the following methods:
Return the name of the sound card used by this Mixer object Return the name of the sound card used by this Mixer object
.. method:: Mixer.mixer() .. method:: Mixer.mixer()
Return the name of the specific mixer controlled by this object, For example Return the name of the specific mixer controlled by this object, For example
``'Master'`` or ``'PCM'`` ``'Master'`` or ``'PCM'``
.. method:: Mixer.mixerid() .. method:: Mixer.mixerid()
Return the ID of the ALSA mixer controlled by this object. Return the ID of the ALSA mixer controlled by this object.
.. method:: Mixer.switchcap() .. method:: Mixer.switchcap()
Returns a list of the switches which are defined by this specific mixer. Returns a list of the switches which are defined by this specific mixer.
@@ -528,6 +373,7 @@ Mixer objects have the following methods:
To manipulate these switches use the :meth:`setrec` or To manipulate these switches use the :meth:`setrec` or
:meth:`setmute` methods :meth:`setmute` methods
.. method:: Mixer.volumecap() .. method:: Mixer.volumecap()
Returns a list of the volume control capabilities of this Returns a list of the volume control capabilities of this
@@ -570,63 +416,58 @@ Mixer objects have the following methods:
This method will return an empty tuple if the mixer is not an enumerated This method will return an empty tuple if the mixer is not an enumerated
control. control.
.. method:: Mixer.setenum(index)
For enumerated controls, sets the currently selected item. .. method:: Mixer.getmute()
*index* is an index into the list of available enumerated items returned
by :func:`getenum`.
.. method:: Mixer.getrange(pcmtype=PCM_PLAYBACK, units=VOLUME_UNITS_RAW) 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])
Return the volume range of the ALSA mixer controlled by this object. 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 *pcmtype* argument can be either :const:`PCM_PLAYBACK` or The optional *direction* argument can be either :const:`PCM_PLAYBACK` or
:const:`PCM_CAPTURE`, which is relevant if the mixer can control both :const:`PCM_CAPTURE`, which is relevant if the mixer can control both
playback and capture volume. The default value is :const:`PCM_PLAYBACK` playback and capture volume. The default value is :const:`PCM_PLAYBACK`
if the mixer has playback channels, otherwise it is :const:`PCM_CAPTURE`. 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.getvolume(pcmtype=PCM_PLAYBACK, units=VOLUME_UNITS_PERCENTAGE) .. 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])
Returns a list with the current volume settings for each channel. The list Returns a list with the current volume settings for each channel. The list
elements are integers whose meaning is determined by the *units* argument. elements are integer percentages.
The optional *pcmtype* argument can be either :const:`PCM_PLAYBACK` or The optional *direction* argument can be either :const:`PCM_PLAYBACK` or
:const:`PCM_CAPTURE`, which is relevant if the mixer can control both :const:`PCM_CAPTURE`, which is relevant if the mixer can control both
playback and capture volume. The default value is :const:`PCM_PLAYBACK` playback and capture volume. The default value is :const:`PCM_PLAYBACK`
if the mixer has playback channels, otherwise it is :const:`PCM_CAPTURE`. 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=None, pcmtype=PCM_PLAYBACK, units=VOLUME_UNITS_PERCENTAGE) .. method:: Mixer.setvolume(volume, [channel], [direction])
Change the current volume settings for this mixer. The *volume* argument Change the current volume settings for this mixer. The *volume* argument
is an integer whose meaning is determined by the *units* argument. controls the new volume setting as an integer percentage.
If the optional argument *channel* is present, the volume is set If the optional argument *channel* is present, the volume is set
only for this channel. This assumes that the mixer can control the only for this channel. This assumes that the mixer can control the
volume for the channels independently. volume for the channels independently.
The optional *pcmtype* argument can be either :const:`PCM_PLAYBACK` or The optional *direction* argument can be either :const:`PCM_PLAYBACK` or
:const:`PCM_CAPTURE`, which is relevant if the mixer can control both :const:`PCM_CAPTURE`, which is relevant if the mixer can control both
playback and capture volume. The default value is :const:`PCM_PLAYBACK` playback and capture volume. The default value is :const:`PCM_PLAYBACK`
if the mixer has playback channels, otherwise it is :const:`PCM_CAPTURE`. 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]) .. method:: Mixer.setmute(mute, [channel])
Sets the mute flag to a new value. The *mute* argument is either 0 for not Sets the mute flag to a new value. The *mute* argument is either 0 for not
@@ -637,12 +478,6 @@ Mixer objects have the following methods:
This method will fail if the mixer has no playback mute capabilities 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]) .. method:: Mixer.setrec(capture, [channel])
@@ -656,22 +491,20 @@ Mixer objects have the following methods:
.. method:: Mixer.polldescriptors() .. method:: Mixer.polldescriptors()
Returns a list of tuples of *(file descriptor, eventmask)* that can be Returns a tuple of *(file descriptor, eventmask)* that can be used to
used to wait for changes on the mixer with *select.poll*. wait for changes on the mixer with *select.poll*.
The *eventmask* value is compatible with `poll.register`__ in the Python The *eventmask* value is compatible with `poll.register`__ in the Python
:const:`select` module. :const:`select` module.
__ poll_objects_
.. method:: Mixer.handleevents() .. method:: Mixer.handleevents()
Acknowledge events on the :func:`polldescriptors` file descriptors Acknowledge events on the *polldescriptors* file descriptors
to prevent subsequent polls from returning the same events again. to prevent subsequent polls from returning the same events again.
Returns the number of events that were acknowledged. Returns the number of events that were acknowledged.
.. method:: Mixer.close()
Closes the Mixer device.
**A rant on the ALSA Mixer API** **A rant on the ALSA Mixer API**
The ALSA mixer API is extremely complicated - and hardly documented at all. The ALSA mixer API is extremely complicated - and hardly documented at all.
@@ -694,6 +527,8 @@ 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 understand half of the API, and that which I do understand has come from a
painful trial and error process. painful trial and error process.
.. % ==== 4. ====
.. _pcm-example: .. _pcm-example:
@@ -735,7 +570,6 @@ To test PCM playback (on your default soundcard), run::
recordtest.py and playbacktest.py recordtest.py and playbacktest.py
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
**recordtest.py** and **playbacktest.py** will record and play a raw **recordtest.py** and **playbacktest.py** will record and play a raw
sound file in CD quality. sound file in CD quality.
@@ -805,3 +639,9 @@ argument::
Capabilities: Playback Volume Playback Mute Capabilities: Playback Volume Playback Mute
Channel 0 volume: 61% Channel 0 volume: 61%
Channel 1 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
+16 -3
View File
@@ -7,12 +7,26 @@ Introduction
.. |release| replace:: version .. |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: .. _front:
This software is licensed under the PSF license - the same one used by the 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 majority of the python distribution. Basically you can use it for anything you
wish (even commercial purposes). There is no warranty whatsoever. 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 .. topic:: Abstract
This package contains wrappers for accessing the ALSA API from Python. It is This package contains wrappers for accessing the ALSA API from Python. It is
@@ -50,8 +64,8 @@ More information about ALSA may be found on the project homepage
ALSA and Python ALSA and Python
=============== ===============
The older Linux sound API (OSS) -- which is now deprecated -- is well supported The older Linux sound API (OSS) which is now deprecated is well supported from
by the standard Python library, through the ossaudiodev module. No native ALSA the standard Python library, through the ossaudiodev module. No native ALSA
support exists in the standard library. support exists in the standard library.
There are a few other "ALSA for Python" projects available, including at least There are a few other "ALSA for Python" projects available, including at least
@@ -92,7 +106,6 @@ And then as root: --- ::
# python setup.py install # python setup.py install
******* *******
Testing Testing
******* *******
+18 -34
View File
@@ -19,7 +19,7 @@ Sample
Musically, the sample size determines the dynamic range. The Musically, the sample size determines the dynamic range. The
dynamic range is the difference between the quietest and the dynamic range is the difference between the quietest and the
loudest signal that can be reproduced. loudest signal that can be resproduced.
Frame Frame
A frame consists of exactly one sample per channel. If there is only one A frame consists of exactly one sample per channel. If there is only one
@@ -29,8 +29,8 @@ Frame
Frame size Frame size
This is the size in bytes of each frame. This can vary a lot: if each sample 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. 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 Similarly in 6 channel audio with 64 bit floating point samples, the frame
is 48 bytes. size is 48 bytes
Rate Rate
PCM sound consists of a flow of sound frames. The sound rate controls how 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. means that a new frame is played or captured 8000 times per second.
Data rate Data rate
This is the number of bytes which must be consumed or provided per This is the number of bytes, which must be recorded or provided per
second at a certain frame size and rate. second at a certain frame size and rate.
8000 Hz mono sound with 8 bit (1 byte) samples has a data rate of 8000 Hz mono sound with 8 bit (1 byte) samples has a data rate of
@@ -46,40 +46,24 @@ Data rate
At the other end of the scale, 96000 Hz, 6 channel sound with 64 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 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 Period
The CPU processes sample data in chunks of frames, so-called periods When the hardware processes data this is done in chunks of frames. The time
(also called fragments by some systems). The operating system kernel's interval between each processing (A/D or D/A conversion) is known
sample buffer must hold at least two periods (at any given time, one as the period.
is processed by the sound hardware, and one by the CPU). 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
The completion of a *period* triggers a CPU interrupt, which causes very small, while low CPU resource usage would usually demand
processing and context switching overhead. Therefore, a smaller period larger period sizes. With ALSA, the CPU utilization is not impacted
size causes higher CPU resource usage at a given data rate. much by the period size, since the kernel layer buffers multiple
periods internally, so each period generates an interrupt and a
A bigger size of the *buffer* improves the system's resilience to xruns. memory copy, but userspace can be slower and read or write multiple
The buffer being split into a bigger number of smaller periods also does periods at the same time.
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 Period size
This is the size of each period in frames. *Not bytes, but frames!* This is the size of each period in Hz. *Not bytes, but Hz!.* In
In :mod:`alsaaudio` the period size is set directly, and it is :mod:`alsaaudio` the period size is set directly, and it is
therefore important to understand the significance of this therefore important to understand the significance of this
number. If the period size is configured to for example 32, number. If the period size is configured to for example 32,
each write should contain exactly 32 frames of sound data, and each each write should contain exactly 32 frames of sound data, and each
+4 -1
View File
@@ -56,7 +56,10 @@ class SinePlayer(Thread):
def __init__(self, frequency = 440.0): def __init__(self, frequency = 440.0):
Thread.__init__(self) Thread.__init__(self)
self.setDaemon(True) self.setDaemon(True)
self.device = alsaaudio.PCM(channels=channels, format=format, rate=sampling_rate) self.device = alsaaudio.PCM()
self.device.setchannels(channels)
self.device.setformat(format)
self.device.setrate(sampling_rate)
self.queue = Queue() self.queue = Queue()
self.change(frequency) self.change(frequency)
+2 -27
View File
@@ -43,36 +43,11 @@ def show_mixer(name, kwargs):
sys.exit(1) sys.exit(1)
print("Mixer name: '%s'" % mixer.mixer()) print("Mixer name: '%s'" % mixer.mixer())
volcap = mixer.volumecap() print("Capabilities: %s %s" % (' '.join(mixer.volumecap()),
print("Capabilities: %s %s" % (' '.join(volcap),
' '.join(mixer.switchcap()))) ' '.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 = mixer.getvolume()
volumes_dB = mixer.getvolume(units=alsaaudio.VOLUME_UNITS_DB)
for i in range(len(volumes)): for i in range(len(volumes)):
print("Channel %i volume: %i%% (%.1f dB)" % (i, volumes[i], volumes_dB[i] / 100.0)) print("Channel %i volume: %i%%" % (i,volumes[i]))
try: try:
mutes = mixer.getmute() mutes = mixer.getmute()
+11 -5
View File
@@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python
# -*- mode: python; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*-
## playbacktest.py ## playbacktest.py
## ##
@@ -39,15 +38,22 @@ if __name__ == '__main__':
f = open(args[0], 'rb') f = open(args[0], 'rb')
# Open the device in playback mode in Mono, 44100 Hz, 16 bit little endian frames # Open the device in playback mode.
out = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK, device=device)
# Set attributes: Mono, 44100 Hz, 16 bit little endian frames
out.setchannels(1)
out.setrate(44100)
out.setformat(alsaaudio.PCM_FORMAT_S16_LE)
# The period size controls the internal number of frames per period. # The period size controls the internal number of frames per period.
# The significance of this parameter is documented in the ALSA api. # The significance of this parameter is documented in the ALSA api.
out.setperiodsize(160)
out = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK, channels=1, rate=44100, format=alsaaudio.PCM_FORMAT_S16_LE, periodsize=160, device=device)
# Read data from stdin # Read data from stdin
data = f.read(320) data = f.read(320)
while data: while data:
out.write(data) out.write(data)
data = f.read(320) data = f.read(320)
out.close()
+16 -14
View File
@@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python
# -*- mode: python; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*-
# Simple test script that plays (some) wav files # Simple test script that plays (some) wav files
@@ -12,29 +11,28 @@ import alsaaudio
def play(device, f): def play(device, f):
format = None print('%d channels, %d sampling rate\n' % (f.getnchannels(),
f.getframerate()))
# Set attributes
device.setchannels(f.getnchannels())
device.setrate(f.getframerate())
# 8bit is unsigned in wav files # 8bit is unsigned in wav files
if f.getsampwidth() == 1: if f.getsampwidth() == 1:
format = alsaaudio.PCM_FORMAT_U8 device.setformat(alsaaudio.PCM_FORMAT_U8)
# Otherwise we assume signed data, little endian # Otherwise we assume signed data, little endian
elif f.getsampwidth() == 2: elif f.getsampwidth() == 2:
format = alsaaudio.PCM_FORMAT_S16_LE device.setformat(alsaaudio.PCM_FORMAT_S16_LE)
elif f.getsampwidth() == 3: elif f.getsampwidth() == 3:
format = alsaaudio.PCM_FORMAT_S24_3LE device.setformat(alsaaudio.PCM_FORMAT_S24_3LE)
elif f.getsampwidth() == 4: elif f.getsampwidth() == 4:
format = alsaaudio.PCM_FORMAT_S32_LE device.setformat(alsaaudio.PCM_FORMAT_S32_LE)
else: else:
raise ValueError('Unsupported format') raise ValueError('Unsupported format')
periodsize = f.getframerate() // 8 periodsize = f.getframerate() // 8
print('%d channels, %d sampling rate, format %d, periodsize %d\n' % (f.getnchannels(), device.setperiodsize(periodsize)
f.getframerate(),
format,
periodsize))
device = alsaaudio.PCM(channels=f.getnchannels(), rate=f.getframerate(), format=format, periodsize=periodsize, device=device)
data = f.readframes(periodsize) data = f.readframes(periodsize)
while data: while data:
@@ -59,5 +57,9 @@ if __name__ == '__main__':
if not args: if not args:
usage() usage()
with wave.open(args[0], 'rb') as f: f = wave.open(args[0], 'rb')
device = alsaaudio.PCM(device=device)
play(device, f) play(device, f)
f.close()
+12 -7
View File
@@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python
# -*- mode: python; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*-
## recordtest.py ## recordtest.py
## ##
@@ -40,8 +39,16 @@ if __name__ == '__main__':
f = open(args[0], 'wb') f = open(args[0], 'wb')
# Open the device in nonblocking capture mode in mono, with a sampling rate of 44100 Hz # Open the device in nonblocking capture mode. The last argument could
# and 16 bit little endian samples # just as well have been zero for blocking mode. Then we could have
# left out the sleep call in the bottom of the loop
inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NONBLOCK, device=device)
# Set attributes: Mono, 44100 Hz, 16 bit little endian samples
inp.setchannels(1)
inp.setrate(44100)
inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
# The period size controls the internal number of frames per period. # The period size controls the internal number of frames per period.
# The significance of this parameter is documented in the ALSA api. # The significance of this parameter is documented in the ALSA api.
# For our purposes, it is suficcient to know that reads from the device # For our purposes, it is suficcient to know that reads from the device
@@ -49,9 +56,7 @@ if __name__ == '__main__':
# This means that the reads below will return either 320 bytes of data # This means that the reads below will return either 320 bytes of data
# or 0 bytes of data. The latter is possible because we are in nonblocking # or 0 bytes of data. The latter is possible because we are in nonblocking
# mode. # mode.
inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NONBLOCK, inp.setperiodsize(160)
channels=1, rate=44100, format=alsaaudio.PCM_FORMAT_S16_LE,
periodsize=160, device=device)
loops = 1000000 loops = 1000000
while loops > 0: while loops > 0:
+1 -1
View File
@@ -8,7 +8,7 @@ from setuptools import setup
from setuptools.extension import Extension from setuptools.extension import Extension
from sys import version from sys import version
pyalsa_version = '0.10.0' pyalsa_version = '0.8.6'
if __name__ == '__main__': if __name__ == '__main__':
setup( setup(
+6 -30
View File
@@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python
# -*- mode: python; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*-
# These are internal tests. They shouldn't fail, but they don't cover all # These are internal tests. They shouldn't fail, but they don't cover all
# of the ALSA API. Most importantly PCM.read and PCM.write are missing. # of the ALSA API. Most importantly PCM.read and PCM.write are missing.
@@ -13,18 +12,13 @@ import alsaaudio
import warnings import warnings
# we can't test read and write well - these are tested otherwise # we can't test read and write well - these are tested otherwise
PCMMethods = [ PCMMethods = [('pcmtype', None),
('pcmtype', None),
('pcmmode', None), ('pcmmode', None),
('cardname', None) ('cardname', None),
]
PCMDeprecatedMethods = [
('setchannels', (2,)), ('setchannels', (2,)),
('setrate', (44100,)), ('setrate', (44100,)),
('setformat', (alsaaudio.PCM_FORMAT_S8,)), ('setformat', (alsaaudio.PCM_FORMAT_S8,)),
('setperiodsize', (320,)) ('setperiodsize', (320,))]
]
# A clever test would look at the Mixer capabilities and selectively run the # A clever test would look at the Mixer capabilities and selectively run the
# omitted tests, but I am too tired for that. # omitted tests, but I am too tired for that.
@@ -135,26 +129,8 @@ class PCMTest(unittest.TestCase):
pass pass
# Verify we got a DepreciationWarning # Verify we got a DepreciationWarning
self.assertEqual(len(w), 1, "PCM(card='default') expected a warning" ) assert len(w) == 1
self.assertTrue(issubclass(w[-1].category, DeprecationWarning), "PCM(card='default') expected a DeprecationWarning") assert issubclass(w[-1].category, DeprecationWarning)
for m, a in PCMDeprecatedMethods:
with warnings.catch_warnings(record=True) as w:
# Cause all warnings to always be triggered.
warnings.simplefilter("always")
pcm = alsaaudio.PCM()
f = alsaaudio.PCM.__dict__[m]
if a is None:
f(pcm)
else:
f(pcm, *a)
# Verify we got a DepreciationWarning
method = "%s%s" % (m, str(a))
self.assertEqual(len(w), 1, method + " expected a warning")
self.assertTrue(issubclass(w[-1].category, DeprecationWarning), method + " expected a DeprecationWarning")
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()