Compare commits

..

17 Commits

Author SHA1 Message Date
Oswald Buddenhagen d0625934bb Merge tag '0.10.0'
the tag was erroneously "orphaned".

fixes #140.

Conflicts:
	CHANGES.md
2024-01-31 20:35:28 +01:00
Lars Immisch 788fcb7c69 Ignore volume events if shairplay-sync is running 2023-11-18 15:41:30 +00:00
Lars Immisch 345260241f loopback.py: bugfixes
Retroactively add to CHANGES.md
2023-10-24 19:17:58 +01:00
Lars Immisch 67adbf0524 Add a (naive) loopback implementation (#132)
* WIP

* Implement alsapcm_polldescriptors_revents and alspcm_avail

* Open/close the playback device when idle.

It takes a long time until it's stopped, though.

* open/close logic of playback device

* Fix opening logic, make period size divisible by 6

* Be less verbose in level info

* Extra argument for output mixer card index

Sometimes, this cannot be deduced from the output device

* Better silence detection

* Run run_after_stop when idle on startup
2023-09-12 21:04:02 +02:00
Lars Immisch cd44517ed5 Improve scope (like in #134) 2023-09-04 13:47:20 +01:00
Lars Immisch 3743cf5bd5 Py_BEGIN_ALLOW_THREADS was in the wrong scope. 2023-09-04 13:45:57 +01:00
Lars Immisch f374adb269 Fix issue #133 2023-09-04 13:43:34 +01:00
Lars Immisch 7cc1dadcb2 Restore previous behaviour of calling snd_pcm_prepare in case of XRUN (#131) 2023-08-31 16:25:42 +02:00
Lars Immisch d3bb44517d Small improvement to VolumeForwarder 2023-06-01 15:29:45 +01:00
Lars Immisch c3dba90ff2 Refactor. SCNR.
The Reactor now takes a callable, and the loopback and volume forwarder are now
implemented as callable instances, which seemed the most Pythonic solution.
2023-06-01 15:16:42 +01:00
Lars Immisch e3ec2d1628 Better error logging and comments 2023-05-31 20:00:16 +01:00
Lars Immisch a66cf02a4c Add volume control forwarding.
This needs the patches from (probably) https://lkml.org/lkml/2021/3/1/419. They are already in the raspberry OS kernel sources and the setup works on a RPi 4
2023-05-30 16:21:53 +01:00
Lars Immisch d5e81f2604 mixertest.py: print capture volume 2023-05-30 14:26:56 +01:00
Lars Immisch 8f7e8fbdfe Add a naive loopback implementation using select.poll()
It does work, though.
2023-05-30 14:07:40 +01:00
Lars Immisch dc3d6c6183 Handle events in alsamixer_getvolume. Closes #126
This issue can be worked around by calling mixer.handleevents() before calling mixer.getvolume(), but it makes more sense to handle all events before returning the volume.
2023-05-12 02:43:51 +01:00
Lars Immisch c6a0c8016d Update changes for release 2023-04-16 00:05:55 +02:00
Oswald Buddenhagen 196ca87a05 assorted improvements (#123)
* 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.

* fix memory leaks in *_polldescriptors()

the calloc'd pollfd arrays were not freed.

* 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`.

* 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.

* fix deprecation warning about PyEval_InitThreads()

PyEval_InitThreads is a no-op in since python 3.9.

* fix deprecation warning about PyUnicode_AsUnicode()

converting to ascii for the purpose of comparison is inefficient.

* remove redundant snd_pcm_hw_params_any() call

we just called it (and even error-checked it) a few lines above.

* add new high-speed samples rates

closes #89 (but alsa doesn't support 768khz yet).

* drop some pointless comments from the tex => sphinx conversion

amends 5c2a00655.

* remove bogus markup from the documentation

the poll objects are linked properly in a different way, and the
footnote appears outdated.

* 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.

* formatting/language fixes in introduction document

* 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.

* 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.

* add some best practices to the docu

addresses #110, among other things.

* 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.

* 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.

* reduce scope of GIL releases

it's pointless to enclose snd_pcm_close() and snd_pcm_pause(), as these
calls don't sleep.

* 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.

* bump (minor) version

we're about to add new features.

* 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().

* 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.

* 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-04-15 21:45:32 +02:00
6 changed files with 113 additions and 300 deletions
+1 -2
View File
@@ -1,6 +1,5 @@
# Version 0.10.1
- revert to not throwing an exception on playback buffer underrun;
instead, return -EPIPE like `PCM.read()` does on overrun; #131
- restore previous xrun behaviour, #131
- type hints
# Version 0.10.0
-1
View File
@@ -1,5 +1,4 @@
include *.py
include alsaaudio.pyi
include CHANGES
include TODO
include LICENSE
+27 -40
View File
@@ -1364,23 +1364,12 @@ alsapcm_read(alsapcm_t *self, PyObject *args)
buffer = PyBytes_AS_STRING(buffer_obj);
#endif
// After drop() and drain(), we need to prepare the stream again.
// Note that fresh streams are already prepared by snd_pcm_hw_params().
state = snd_pcm_state(self->handle);
if ((state != SND_PCM_STATE_SETUP) ||
!(res = snd_pcm_prepare(self->handle))) {
if ((state != SND_PCM_STATE_XRUN && state != SND_PCM_STATE_SETUP) ||
(res = snd_pcm_prepare(self->handle)) >= 0) {
Py_BEGIN_ALLOW_THREADS
res = snd_pcm_readi(self->handle, buffer, self->periodsize);
Py_END_ALLOW_THREADS
if (res == -EPIPE) {
// This means buffer overrun, which we need to report.
// However, we recover the stream, so the next PCM.read() will work
// again. If recovery fails (very unlikely), report that instead.
if (!(res = snd_pcm_prepare(self->handle)))
res = -EPIPE;
}
}
if (res != -EPIPE)
@@ -1396,10 +1385,10 @@ alsapcm_read(alsapcm_t *self, PyObject *args)
Py_DECREF(buffer_obj);
return NULL;
}
else
{
sizeout = res * self->framesize;
}
}
if (res > 0 ) {
sizeout = res * self->framesize;
}
if (size != sizeout) {
@@ -1436,6 +1425,7 @@ static PyObject *alsapcm_write(alsapcm_t *self, PyObject *args)
{
int datalen;
char *data;
PyObject *rc = NULL;
#if PY_MAJOR_VERSION < 3
if (!PyArg_ParseTuple(args,"s#:write", &data, &datalen))
@@ -1473,48 +1463,45 @@ static PyObject *alsapcm_write(alsapcm_t *self, PyObject *args)
}
int res;
// After drop() and drain(), we need to prepare the stream again.
// Note that fresh streams are already prepared by snd_pcm_hw_params().
snd_pcm_state_t state = snd_pcm_state(self->handle);
if ((state != SND_PCM_STATE_SETUP) ||
!(res = snd_pcm_prepare(self->handle))) {
if ((state != SND_PCM_STATE_XRUN && state != SND_PCM_STATE_SETUP) ||
(res = snd_pcm_prepare(self->handle)) >= 0) {
Py_BEGIN_ALLOW_THREADS
res = snd_pcm_writei(self->handle, data, datalen/self->framesize);
Py_END_ALLOW_THREADS
if (res == -EPIPE) {
// This means buffer underrun, which we need to report.
// However, we recover the stream, so the next PCM.write() will work
// again. If recovery fails (very unlikely), report that instead.
if (!(res = snd_pcm_prepare(self->handle)))
res = -EPIPE;
/* EPIPE means underrun */
res = snd_pcm_recover(self->handle, res, 1);
if (res >= 0) {
res = snd_pcm_writei(self->handle, data, datalen/self->framesize);
}
}
Py_END_ALLOW_THREADS
}
if (res != -EPIPE)
if (res == -EAGAIN) {
rc = PyLong_FromLong(0);
}
res = snd_pcm_prepare(self->handle);
if (res < 0)
{
if (res == -EAGAIN)
{
res = 0;
}
else if (res < 0) {
PyErr_Format(ALSAAudioError, "%s [%s]", snd_strerror(res),
self->cardname);
PyErr_Format(ALSAAudioError, "%s [%s]", snd_strerror(res),
self->cardname);
#if PY_MAJOR_VERSION >= 3
PyBuffer_Release(&buf);
PyBuffer_Release(&buf);
#endif
return NULL;
}
return NULL;
}
#if PY_MAJOR_VERSION >= 3
PyBuffer_Release(&buf);
#endif
return PyLong_FromLong(res);
return rc;
}
static PyObject *
-128
View File
@@ -1,128 +0,0 @@
from typing import list
PCM_PLAYBACK: int
PCM_CAPTURE: int
PCM_NORMAL: int
PCM_NONBLOCK: int
PCM_ASYNC: int
PCM_FORMAT_S8: int
PCM_FORMAT_U8: int
PCM_FORMAT_S16_LE: int
PCM_FORMAT_S16_BE: int
PCM_FORMAT_U16_LE: int
PCM_FORMAT_U16_BE: int
PCM_FORMAT_S24_LE: int
PCM_FORMAT_S24_BE: int
PCM_FORMAT_U24_LE: int
PCM_FORMAT_U24_BE: int
PCM_FORMAT_S32_LE: int
PCM_FORMAT_S32_BE: int
PCM_FORMAT_U32_LE: int
PCM_FORMAT_U32_BE: int
PCM_FORMAT_FLOAT_LE: int
PCM_FORMAT_FLOAT_BE: int
PCM_FORMAT_FLOAT64_LE: int
PCM_FORMAT_FLOAT64_BE: int
PCM_FORMAT_MU_LAW: int
PCM_FORMAT_A_LAW: int
PCM_FORMAT_IMA_ADPCM: int
PCM_FORMAT_MPEG: int
PCM_FORMAT_GSM: int
PCM_FORMAT_S24_3LE: int
PCM_FORMAT_S24_3BE: int
PCM_FORMAT_U24_3LE: int
PCM_FORMAT_U24_3BE: int
PCM_TSTAMP_NONE: int
PCM_TSTAMP_ENABLE: int
PCM_TSTAMP_TYPE_GETTIMEOFDAY: int
PCM_TSTAMP_TYPE_MONOTONIC: int
PCM_TSTAMP_TYPE_MONOTONIC_RAW: int
PCM_FORMAT_DSD_U8: int
PCM_FORMAT_DSD_U16_LE: int
PCM_FORMAT_DSD_U32_LE: int
PCM_FORMAT_DSD_U32_BE: int
PCM_STATE_OPEN: int
PCM_STATE_SETUP: int
PCM_STATE_PREPARED: int
PCM_STATE_RUNNING: int
PCM_STATE_XRUN: int
PCM_STATE_DRAINING: int
PCM_STATE_PAUSED: int
PCM_STATE_SUSPENDED: int
PCM_STATE_DISCONNECTED: int
MIXER_CHANNEL_ALL: int
MIXER_SCHN_UNKNOWN: int
MIXER_SCHN_FRONT_LEFT: int
MIXER_SCHN_FRONT_RIGHT: int
MIXER_SCHN_REAR_LEFT: int
MIXER_SCHN_REAR_RIGHT: int
MIXER_SCHN_FRONT_CENTER: int
MIXER_SCHN_WOOFER: int
MIXER_SCHN_SIDE_LEFT: int
MIXER_SCHN_SIDE_RIGHT: int
MIXER_SCHN_REAR_CENTER: int
MIXER_SCHN_MONO: int
VOLUME_UNITS_PERCENTAGE: int
VOLUME_UNITS_RAW: int
VOLUME_UNITS_DB: int
def pcms(pcmtype:int) -> list[str]: ...
def cards() -> list[str]: ...
def mixers(cardindex:int=-1, device:str='default') -> list[str]: ...
def asoundlib_version() -> str: ...
class PCM:
def __init__(type:int=PCM_PLAYBACK, mode:int=PCM_NORMAL, rate:int=44100, channels:int=2,
format:int=PCM_FORMAT_S16_LE, periodsize:int=32, periods:int=4,
device:str='default', cardindex:int=-1) -> PCM: ...
def info() -> dict: ...
def pcmtype() -> int: ...
def pcmmode() -> int: ...
def cardname() -> str: ...
def setchannels(nchannels: int) -> None: ...
def setrate(rate: int) -> None: ...
def setformat(format: int) -> int: ...
def setperiodsize(period: int) -> int: ...
def dumpinfo() -> None: ...
def state() -> int: ...
def read() -> tuple[int, bytes]: ...
def write(data:bytes) -> int: ...
def pause(enable:bool=True) -> int: ...
def drop() -> int: ...
def drain() -> int: ...
def polldescriptors() -> list[tuple[int, int]]: ...
def set_tstamp_mode(mode:int=PCM_TSTAMP_ENABLE) -> None: ...
def get_tstamp_mode() -> int: ...
def set_tstamp_type(type:int=PCM_TSTAMP_TYPE_GETTIMEOFDAY) -> None: ...
def get_tstamp_type() -> int: ...
def htimestamp() -> tuple[int, int, int]: ...
class Mixer:
def __init__(control:str='Master', id:int=0, cardindex:int=-1, device:str='default') -> Mixer: ...
def cardname() -> str: ...
def mixer() -> str: ...
def mixerid() -> int: ...
def switchcap() -> int: ...
def volumecap() -> int: ...
def getenum() -> tuple[ str, list[str]]: ...
def setenum(index:int) -> None: ...
def getrange(pcmtype:int=PCM_PLAYBACK, units:int=VOLUME_UNITS_RAW) -> tuple[int, int]: ...
def getvolume(pcmtype:int=PCM_PLAYBACK, units:int=VOLUME_UNITS_PERCENTAGE) -> int: ...
def setvolume(volume:int, pcmtype:int=PCM_PLAYBACK, units:int=VOLUME_UNITS_PERCENTAGE, channel:int|None=None) -> None: ...
def getmute() -> list[int]: ...
def setmute(mute:bool, channel:int|None=None) -> None: ...
def getrec() -> list[int]: ...
def setrec(capture:int, channel:int|None=None) -> None: ...
def polldescriptors() -> list[tuple[int, int]]: ...
def close() -> None: ...
+85 -89
View File
@@ -10,14 +10,14 @@
The :mod:`alsaaudio` module defines functions and classes for using ALSA.
.. function:: pcms(pcmtype:int=PCM_PLAYBACK) ->list[str]
.. function:: pcms(pcmtype=PCM_PLAYBACK)
List available PCM devices by name.
Arguments are:
* *pcmtype* - can be either :const:`PCM_CAPTURE` or :const:`PCM_PLAYBACK`
(default).
(default).
**Note:**
@@ -34,7 +34,7 @@ The :mod:`alsaaudio` module defines functions and classes for using ALSA.
*New in 0.8*
.. function:: cards() -> list[str]
.. function:: cards()
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`
@@ -96,18 +96,18 @@ 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, periods=4, device='default', cardindex=-1) -> PCM
.. 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:
* *type* - can be either :const:`PCM_CAPTURE` or :const:`PCM_PLAYBACK`
(default).
(default).
* *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``.
* *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.
* *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`.
========================= ===============
@@ -179,24 +179,24 @@ following arguments:
PCM objects have the following methods:
.. method:: PCM.info() -> dict
.. 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
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
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 PCM():format integer
format_name PCM():format string
format_description PCM():format string
subformat_name *name of PCM subformat* string
@@ -219,13 +219,13 @@ PCM objects have the following methods:
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)
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() -> int
.. method:: PCM.pcmtype()
Returns the type of PCM object. Either :const:`PCM_CAPTURE` or
:const:`PCM_PLAYBACK`.
@@ -267,29 +267,37 @@ PCM objects have the following methods:
Returns a dictionary of supported format codes (integers) keyed by
their standard ALSA names (strings).
.. method:: PCM.setchannels(nchannels: int) -> int
.. method:: PCM.setchannels(nchannels)
.. deprecated:: 0.9 Use the `channels` named argument to :func:`PCM`.
.. method:: PCM.setrate(rate: int) -> int
.. method:: PCM.setrate(rate)
.. deprecated:: 0.9 Use the `rate` named argument to :func:`PCM`.
.. method:: PCM.setformat(format: int) -> int
.. method:: PCM.setformat(format)
.. deprecated:: 0.9 Use the `format` named argument to :func:`PCM`.
.. method:: PCM.setperiodsize(period: int) -> int
.. 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() -> None
.. method:: PCM.dumpinfo()
Dumps the PCM object's configured parameters to stdout.
.. method:: PCM.state() -> int
.. method:: PCM.state()
Returs the current state of the stream, which can be one of
:const:`PCM_STATE_OPEN` (this should not actually happen),
@@ -304,66 +312,54 @@ PCM objects have the following methods:
*New in 0.10*
.. method:: PCM.read() -> tuple[int, bytes]
.. method:: PCM.read()
In :const:`PCM_NORMAL` mode, this function blocks until a full period is
available, and then returns a tuple (length,data) where *length* is
the number of frames of captured data, and *data* is the captured
sound frames as a string. The length of the returned data will be
sound frames as a string. The length of the returned data will be
periodsize\*framesize bytes.
In :const:`PCM_NONBLOCK` mode, the call will not block, but will return
``(0,'')`` if no new period has become available since the last
call to read.
In case of a buffer overrun, this function will return the negative
size :const:`-EPIPE`, and no data is read.
This indicates that data was lost. To resume capturing, just call read
again, but note that the stream was already corrupted.
To avoid the problem in the future, try using a larger period size
and/or more periods, at the cost of higher latency.
In case of an overrun, this function will return a negative size: :const:`-EPIPE`.
This indicates that data was lost, even if the operation itself succeeded.
Try using a larger periodsize.
.. method:: PCM.write(data: bytes) -> int
.. method:: PCM.write(data)
Writes (plays) the sound in data. The length of data *must* be a
multiple of the frame size, and *should* be exactly the size of a
period. If less than 'period size' frames are provided, the actual
playout will not happen until more data is written.
If the data was successfully written, the call returns the size of the
data *in frames*.
If the device is not in :const:`PCM_NONBLOCK` mode, this call will block
if the kernel buffer is full, and until enough sound has been played
to allow the sound data to be buffered.
If the device is not in :const:`PCM_NONBLOCK` mode, this call will block if
the kernel buffer is full, and until enough sound has been played
to allow the sound data to be buffered. The call always returns the
size of the data provided.
In :const:`PCM_NONBLOCK` mode, the call will return immediately, with a
return value of zero, if the buffer is full. In this case, the data
should be written again at a later time.
In case of a buffer underrun, this function will return the negative
size :const:`-EPIPE`, and no data is written.
At this point, the playback was already corrupted. If you want to play
the data nonetheless, call write again with the same data.
To avoid the problem in the future, try using a larger period size
and/or more periods, at the cost of higher latency.
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]) -> int
.. method:: PCM.pause([enable=True])
If *enable* is :const:`True`, playback or capture is paused.
Otherwise, playback/capture is resumed.
.. method:: PCM.drop() -> int
.. method:: PCM.drop()
Stop the stream and drop residual buffered frames.
*New in 0.9*
.. method:: PCM.drain() -> int
.. method:: PCM.drain()
For :const:`PCM_PLAYBACK` PCM objects, play residual buffered frames
and then stop the stream. In :const:`PCM_NORMAL` mode,
@@ -373,37 +369,44 @@ PCM objects have the following methods:
*New in 0.10*
.. method:: PCM.polldescriptors() -> list[tuple[int, int]]
.. 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 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
The *eventmask* value is compatible with `poll.register`__ in the Python
:const:`select` module.
.. method:: PCM.set_tstamp_mode([mode=PCM_TSTAMP_ENABLE]) -> None
.. 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() -> int
.. 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]) -> None
.. 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() -> int
.. 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() -> tuple[int, int, int]
.. method:: PCM.htimestamp()
Return a Python tuple *(seconds, nanoseconds, frames_available_in_buffer)*.
@@ -430,16 +433,9 @@ PCM objects have the following methods:
update.
================================= ===========================================
.. method:: PCM.close() -> None
Closes the PCM device.
For :const:`PCM_PLAYBACK` PCM objects in :const:`PCM_NORMAL` mode,
this function blocks until all pending playback is drained.
**A few hints on using PCM devices for playback**
The most common reason for problems with playback of PCM audio is that writes
The most common reason for problems with playback of PCM audio is that writes
to PCM devices must *exactly* match the data rate of the device.
If too little data is written to the device, it will underrun, and
@@ -472,12 +468,12 @@ Mixer Objects
Mixer objects provides access to the ALSA mixer API.
.. class:: Mixer(control='Master', id=0, cardindex=-1, device='default') -> Mixer
.. 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
object. The list of available controls can be found with the
:mod:`alsaaudio`.\ :func:`mixers` function. The default value is
``'Master'`` - other common controls may be ``'Master Mono'``, ``'PCM'``,
``'Line'``, etc.
@@ -487,7 +483,7 @@ Mixer objects provides access to the ALSA mixer API.
* *cardindex* - specifies which card should be used. If this argument
is given, the device name is constructed like this: 'hw:*cardindex*' and
the `device` keyword argument is ignored. ``0`` is the
first sound card.
first sound card.
* *device* - the name of the device on which the mixer resides. The default
value is ``'default'``.
@@ -499,20 +495,20 @@ Mixer objects provides access to the ALSA mixer API.
Mixer objects have the following methods:
.. method:: Mixer.cardname() -> str
.. method:: Mixer.cardname()
Return the name of the sound card used by this Mixer object
.. method:: Mixer.mixer() -> str
.. method:: Mixer.mixer()
Return the name of the specific mixer controlled by this object, For example
``'Master'`` or ``'PCM'``
.. method:: Mixer.mixerid() -> int
.. method:: Mixer.mixerid()
Return the ID of the ALSA mixer controlled by this object.
.. method:: Mixer.switchcap() -> int
.. method:: Mixer.switchcap()
Returns a list of the switches which are defined by this specific mixer.
Possible values in this list are:
@@ -524,7 +520,7 @@ Mixer objects have the following methods:
'Joined Mute' This mixer can mute all channels at the same time
'Playback Mute' This mixer can mute the playback output
'Joined Playback Mute' Mute playback for all channels at the same time}
'Capture Mute' Mute sound capture
'Capture Mute' Mute sound capture
'Joined Capture Mute' Mute sound capture for all channels at a time}
'Capture Exclusive' Not quite sure what this is
====================== ================
@@ -532,7 +528,7 @@ Mixer objects have the following methods:
To manipulate these switches use the :meth:`setrec` or
:meth:`setmute` methods
.. method:: Mixer.volumecap() -> int
.. method:: Mixer.volumecap()
Returns a list of the volume control capabilities of this
mixer. Possible values in the list are:
@@ -548,7 +544,7 @@ Mixer objects have the following methods:
'Joined Capture Volume' Manipulate sound capture volume for all channels at a time
======================== ================
.. method:: Mixer.getenum() -> tuple[ str, list[str]]
.. method:: Mixer.getenum()
For enumerated controls, return the currently selected item and the list of
items available.
@@ -574,13 +570,13 @@ 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:int) -> None
.. method:: Mixer.setenum(index)
For enumerated controls, sets the currently selected item.
*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) -> tuple[int, int]
.. 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
@@ -594,7 +590,7 @@ Mixer objects have the following methods:
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:int=PCM_PLAYBACK, units:int=VOLUME_UNITS_PERCENTAGE) -> int
.. 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 integers whose meaning is determined by the *units* argument.
@@ -607,7 +603,7 @@ Mixer objects have the following methods:
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:int, pcmtype:int=PCM_PLAYBACK, units:int=VOLUME_UNITS_PERCENTAGE, channel:int|None) -> None
.. method:: Mixer.setvolume(volume, channel=None, pcmtype=PCM_PLAYBACK, units=VOLUME_UNITS_PERCENTAGE)
Change the current volume settings for this mixer. The *volume* argument
is an integer whose meaning is determined by the *units* argument.
@@ -624,14 +620,14 @@ Mixer objects have the following methods:
The optional *units* argument can be one of :const:`VOLUME_UNITS_PERCENTAGE`,
:const:`VOLUME_UNITS_RAW`, or :const:`VOLUME_UNITS_DB`.
.. method:: Mixer.getmute() -> list[int]
.. 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:bool, channel:int|None=None) -> None
.. method:: Mixer.setmute(mute, [channel])
Sets the mute flag to a new value. The *mute* argument is either 0 for not
muted, or 1 for muted.
@@ -641,14 +637,14 @@ Mixer objects have the following methods:
This method will fail if the mixer has no playback mute capabilities
.. method:: Mixer.getrec() -> list[int]
.. 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:int, channel:int|None=None) -> None
.. method:: Mixer.setrec(capture, [channel])
Sets the capture mute flag to a new value. The *capture* argument
is either 0 for no capture, or 1 for capture.
@@ -658,21 +654,21 @@ Mixer objects have the following methods:
This method will fail if the mixer has no capture switch capabilities.
.. method:: Mixer.polldescriptors() -> list[tuple[int, int]]
.. method:: Mixer.polldescriptors()
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
The *eventmask* value is compatible with `poll.register`__ in the Python
:const:`select` module.
.. method:: Mixer.handleevents() -> int
.. method:: Mixer.handleevents()
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() -> None
.. method:: Mixer.close()
Closes the Mixer device.
@@ -711,7 +707,7 @@ The following example are provided:
* `playbacktest.py`
* `mixertest.py`
All examples (except `mixertest.py`) accept the commandline option
All examples (except `mixertest.py`) accept the commandline option
*-c <cardname>*.
To determine a valid card name, use the commandline ALSA player::
@@ -726,12 +722,12 @@ or::
>>> alsaaudio.pcms()
mixertest.py accepts the commandline options *-d <device>* and
*-c <cardindex>*.
*-c <cardindex>*.
playwav.py
~~~~~~~~~~
**playwav.py** plays a wav file.
**playwav.py** plays a wav file.
To test PCM playback (on your default soundcard), run::
@@ -779,7 +775,7 @@ The output might look like this::
'Mix'
'Mix Mono'
With a single argument - the *control*, it will display the settings of
With a single argument - the *control*, it will display the settings of
that control; for example::
$ ./mixertest.py Master
@@ -788,7 +784,7 @@ that control; for example::
Channel 0 volume: 61%
Channel 1 volume: 61%
With two arguments, the *control* and a *parameter*, it will set the
With two arguments, the *control* and a *parameter*, it will set the
parameter on the mixer::
$ ./mixertest.py Master mute
-40
View File
@@ -1,40 +0,0 @@
#!/usr/bin/env python3
# -*- mode: python; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*-
import alsaaudio
import select
def echo(inpcm, outpcm):
q = list()
# setup the synchronous event loop
# See https://docs.python.org/3/library/select.html#poll-objects for background
reactor = select.poll()
infd, inmask = inpcm.polldecriptors()
outfd, outmask = outpcm.polldescriptors()
write_started = False
def write():
data = q.pop()
written = outpcm.write(data)
if written < len(data):
q.insert(0, data[written:])
reactor.register(infd, inmask)
reactor.register(outfd, outmask)
while True:
events = reactor.poll()
for fd, event in events:
if event == select.POLLIN and fd == infd:
data = inpcm.read()
q.append(data)
if not write_started:
write()
write_started = True
elif event == select.POLLOUT and fd == outfd:
if not q:
return
write()