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
16 changed files with 235 additions and 496 deletions
+3 -14
View File
@@ -1,17 +1,6 @@
# Version 0.11.0 # Version 0.10.1
- Fixed `Mixer.getvolume()` returning outdated value (#126) - restore previous xrun behaviour, #131
- Fixed PCM crashing with some sample formats due to buffer size - type hints
miscalculation
- Fixed `PCM.read()` ignoring overruns (regression in 0.10.0)
- Reverted to `PCM.write()` not throwing an exception on playback buffer
underrun; instead, return -EPIPE like `PCM.read()` does on overrun (#130)
- Added `PCM.avail()` and `PCM.polldescriptors_revents()` functions
- Added `nominal_bits` and `physical_bits` entries to `PCM.info()`'s
return value
- Added Python type hint file, and adjusted documentation accordingly (#58)
- Improvements to the examples, in particular isine.py (#42)
Contributions by @ossilator and @viinikv.
# Version 0.10.0 # Version 0.10.0
- assorted improvements (#123 from @ossilator) - assorted improvements (#123 from @ossilator)
-1
View File
@@ -1,5 +1,4 @@
include *.py include *.py
include *.pyi
include CHANGES include CHANGES
include TODO include TODO
include LICENSE include LICENSE
+55 -84
View File
@@ -403,7 +403,7 @@ static int alsapcm_setup(alsapcm_t *self)
snd_pcm_hw_params_get_period_size(hwparams, &self->periodsize, &dir); snd_pcm_hw_params_get_period_size(hwparams, &self->periodsize, &dir);
snd_pcm_hw_params_get_periods(hwparams, &self->periods, &dir); snd_pcm_hw_params_get_periods(hwparams, &self->periods, &dir);
self->framesize = self->channels * snd_pcm_format_physical_width(self->format)/8; self->framesize = self->channels * snd_pcm_hw_params_get_sbits(hwparams)/8;
return res; return res;
} }
@@ -598,12 +598,6 @@ alsapcm_dumpinfo(alsapcm_t *self, PyObject *args)
val = snd_pcm_hw_params_get_sbits(hwparams); val = snd_pcm_hw_params_get_sbits(hwparams);
printf("significant bits = %d\n", val); printf("significant bits = %d\n", val);
val = snd_pcm_format_width(self->format);
printf("nominal bits = %d\n", val);
val = snd_pcm_format_physical_width(self->format);
printf("physical bits = %d\n", val);
val = snd_pcm_hw_params_is_batch(hwparams); val = snd_pcm_hw_params_is_batch(hwparams);
printf("is batch = %d\n", val); printf("is batch = %d\n", val);
@@ -784,16 +778,6 @@ alsapcm_info(alsapcm_t *self, PyObject *args)
PyDict_SetItemString(info,"significant_bits", value); PyDict_SetItemString(info,"significant_bits", value);
Py_DECREF(value); Py_DECREF(value);
val = snd_pcm_format_width(self->format);
value=PyLong_FromUnsignedLong((unsigned long) val);
PyDict_SetItemString(info,"nominal_bits", value);
Py_DECREF(value);
val = snd_pcm_format_physical_width(self->format);
value=PyLong_FromUnsignedLong((unsigned long) val);
PyDict_SetItemString(info,"physical_bits", value);
Py_DECREF(value);
val = snd_pcm_hw_params_is_batch(hwparams); val = snd_pcm_hw_params_is_batch(hwparams);
value=PyBool_FromLong((unsigned long) val); value=PyBool_FromLong((unsigned long) val);
PyDict_SetItemString(info,"is_batch", value); PyDict_SetItemString(info,"is_batch", value);
@@ -1170,37 +1154,6 @@ alsapcm_getchannels(alsapcm_t *self,PyObject *args)
return out; return out;
} }
static PyObject *
alsapcm_setchannels(alsapcm_t *self, PyObject *args)
{
int channels, saved;
int res;
if (!PyArg_ParseTuple(args,"i:setchannels", &channels))
return NULL;
if (!self->handle) {
PyErr_SetString(ALSAAudioError, "PCM device is closed");
return NULL;
}
PyErr_WarnEx(PyExc_DeprecationWarning,
"This function is deprecated. "
"Please use the named parameter `channels` to `PCM()` instead", 1);
saved = self->channels;
self->channels = channels;
res = alsapcm_setup(self);
if (res < 0)
{
self->channels = saved;
PyErr_Format(ALSAAudioError, "%s [%s]", snd_strerror(res),
self->cardname);
return NULL;
}
return PyLong_FromLong(self->channels);
}
static PyObject * static PyObject *
alsapcm_pcmtype(alsapcm_t *self, PyObject *args) alsapcm_pcmtype(alsapcm_t *self, PyObject *args)
{ {
@@ -1243,6 +1196,37 @@ alsapcm_cardname(alsapcm_t *self, PyObject *args)
return PyUnicode_FromString(self->cardname); return PyUnicode_FromString(self->cardname);
} }
static PyObject *
alsapcm_setchannels(alsapcm_t *self, PyObject *args)
{
int channels, saved;
int res;
if (!PyArg_ParseTuple(args,"i:setchannels", &channels))
return NULL;
if (!self->handle) {
PyErr_SetString(ALSAAudioError, "PCM device is closed");
return NULL;
}
PyErr_WarnEx(PyExc_DeprecationWarning,
"This function is deprecated. "
"Please use the named parameter `channels` to `PCM()` instead", 1);
saved = self->channels;
self->channels = channels;
res = alsapcm_setup(self);
if (res < 0)
{
self->channels = saved;
PyErr_Format(ALSAAudioError, "%s [%s]", snd_strerror(res),
self->cardname);
return NULL;
}
return PyLong_FromLong(self->channels);
}
static PyObject * static PyObject *
alsapcm_setrate(alsapcm_t *self, PyObject *args) alsapcm_setrate(alsapcm_t *self, PyObject *args)
{ {
@@ -1380,23 +1364,12 @@ alsapcm_read(alsapcm_t *self, PyObject *args)
buffer = PyBytes_AS_STRING(buffer_obj); buffer = PyBytes_AS_STRING(buffer_obj);
#endif #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); state = snd_pcm_state(self->handle);
if ((state != SND_PCM_STATE_SETUP) || if ((state != SND_PCM_STATE_XRUN && state != SND_PCM_STATE_SETUP) ||
!(res = snd_pcm_prepare(self->handle))) { (res = snd_pcm_prepare(self->handle)) >= 0) {
Py_BEGIN_ALLOW_THREADS Py_BEGIN_ALLOW_THREADS
res = snd_pcm_readi(self->handle, buffer, self->periodsize); res = snd_pcm_readi(self->handle, buffer, self->periodsize);
Py_END_ALLOW_THREADS 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) if (res != -EPIPE)
@@ -1412,10 +1385,10 @@ alsapcm_read(alsapcm_t *self, PyObject *args)
Py_DECREF(buffer_obj); Py_DECREF(buffer_obj);
return NULL; return NULL;
} }
else
{
sizeout = res * self->framesize;
} }
if (res > 0 ) {
sizeout = res * self->framesize;
} }
if (size != sizeout) { if (size != sizeout) {
@@ -1452,6 +1425,7 @@ static PyObject *alsapcm_write(alsapcm_t *self, PyObject *args)
{ {
int datalen; int datalen;
char *data; char *data;
PyObject *rc = NULL;
#if PY_MAJOR_VERSION < 3 #if PY_MAJOR_VERSION < 3
if (!PyArg_ParseTuple(args,"s#:write", &data, &datalen)) if (!PyArg_ParseTuple(args,"s#:write", &data, &datalen))
@@ -1489,32 +1463,30 @@ static PyObject *alsapcm_write(alsapcm_t *self, PyObject *args)
} }
int res; 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); 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 Py_BEGIN_ALLOW_THREADS
res = snd_pcm_writei(self->handle, data, datalen/self->framesize); res = snd_pcm_writei(self->handle, data, datalen/self->framesize);
Py_END_ALLOW_THREADS
if (res == -EPIPE) { if (res == -EPIPE) {
// This means buffer underrun, which we need to report. /* EPIPE means underrun */
// However, we recover the stream, so the next PCM.write() will work res = snd_pcm_recover(self->handle, res, 1);
// again. If recovery fails (very unlikely), report that instead. if (res >= 0) {
if (!(res = snd_pcm_prepare(self->handle))) res = snd_pcm_writei(self->handle, data, datalen/self->framesize);
res = -EPIPE;
} }
} }
Py_END_ALLOW_THREADS
}
if (res != -EPIPE) if (res == -EAGAIN) {
{ rc = PyLong_FromLong(0);
if (res == -EAGAIN)
{
res = 0;
} }
else if (res < 0) { res = snd_pcm_prepare(self->handle);
if (res < 0)
{
PyErr_Format(ALSAAudioError, "%s [%s]", snd_strerror(res), PyErr_Format(ALSAAudioError, "%s [%s]", snd_strerror(res),
self->cardname); self->cardname);
@@ -1524,13 +1496,12 @@ static PyObject *alsapcm_write(alsapcm_t *self, PyObject *args)
return NULL; return NULL;
} }
}
#if PY_MAJOR_VERSION >= 3 #if PY_MAJOR_VERSION >= 3
PyBuffer_Release(&buf); PyBuffer_Release(&buf);
#endif #endif
return PyLong_FromLong(res); return rc;
} }
static PyObject * static PyObject *
@@ -1750,7 +1721,6 @@ static PyMethodDef alsapcm_methods[] = {
{"pcmtype", (PyCFunction)alsapcm_pcmtype, METH_VARARGS}, {"pcmtype", (PyCFunction)alsapcm_pcmtype, METH_VARARGS},
{"pcmmode", (PyCFunction)alsapcm_pcmmode, METH_VARARGS}, {"pcmmode", (PyCFunction)alsapcm_pcmmode, METH_VARARGS},
{"cardname", (PyCFunction)alsapcm_cardname, METH_VARARGS}, {"cardname", (PyCFunction)alsapcm_cardname, METH_VARARGS},
{"getchannels", (PyCFunction)alsapcm_getchannels, METH_VARARGS},
{"setchannels", (PyCFunction)alsapcm_setchannels, METH_VARARGS}, {"setchannels", (PyCFunction)alsapcm_setchannels, METH_VARARGS},
{"setrate", (PyCFunction)alsapcm_setrate, METH_VARARGS}, {"setrate", (PyCFunction)alsapcm_setrate, METH_VARARGS},
{"setformat", (PyCFunction)alsapcm_setformat, METH_VARARGS}, {"setformat", (PyCFunction)alsapcm_setformat, METH_VARARGS},
@@ -1766,6 +1736,7 @@ static PyMethodDef alsapcm_methods[] = {
{"getformats", (PyCFunction)alsapcm_getformats, METH_VARARGS}, {"getformats", (PyCFunction)alsapcm_getformats, METH_VARARGS},
{"getratebounds", (PyCFunction)alsapcm_getratemaxmin, METH_VARARGS}, {"getratebounds", (PyCFunction)alsapcm_getratemaxmin, METH_VARARGS},
{"getrates", (PyCFunction)alsapcm_getrates, METH_VARARGS}, {"getrates", (PyCFunction)alsapcm_getrates, METH_VARARGS},
{"getchannels", (PyCFunction)alsapcm_getchannels, METH_VARARGS},
{"read", (PyCFunction)alsapcm_read, METH_VARARGS}, {"read", (PyCFunction)alsapcm_read, METH_VARARGS},
{"write", (PyCFunction)alsapcm_write, METH_VARARGS}, {"write", (PyCFunction)alsapcm_write, METH_VARARGS},
{"avail", (PyCFunction)alsapcm_avail, METH_VARARGS}, {"avail", (PyCFunction)alsapcm_avail, METH_VARARGS},
-135
View File
@@ -1,135 +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 close() -> None: ...
def dumpinfo() -> None: ...
def info() -> dict: ...
def state() -> int: ...
def htimestamp() -> tuple[int, 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 getformats() -> dict: ...
def getratebounds() -> tuple[int, int]: ...
def getrates() -> int | tuple[int, int] | list[int]: ...
def getchannels() -> list[int]: ...
def setchannels(nchannels: int) -> None: ...
def pcmtype() -> int: ...
def pcmmode() -> int: ...
def cardname() -> str: ...
def setrate(rate: int) -> None: ...
def setformat(format: int) -> int: ...
def setperiodsize(period: int) -> int: ...
def read() -> tuple[int, bytes]: ...
def write(data: bytes) -> int: ...
def avail() -> int: ...
def pause(enable: bool = True) -> int: ...
def drop() -> int: ...
def drain() -> int: ...
def polldescriptors() -> list[tuple[int, int]]: ...
def polldescriptors_revents(descriptors: list[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 close() -> None: ...
def mixer() -> str: ...
def mixerid() -> int: ...
def switchcap() -> int: ...
def volumecap() -> int: ...
def getvolume(pcmtype: int = PCM_PLAYBACK, units: int = VOLUME_UNITS_PERCENTAGE) -> int: ...
def getrange(pcmtype: int = PCM_PLAYBACK, units: int = VOLUME_UNITS_RAW) -> tuple[int, int]: ...
def getenum() -> tuple[str, list[str]]: ...
def getmute() -> list[int]: ...
def getrec() -> list[int]: ...
def setvolume(volume: int, pcmtype: int = PCM_PLAYBACK, units: int = VOLUME_UNITS_PERCENTAGE, channel: (int | None) = None) -> None: ...
def setenum(index: int) -> None: ...
def setmute(mute: bool, channel: (int | None) = None) -> None: ...
def setrec(capture: int, channel: (int | None) = None) -> None: ...
def polldescriptors() -> list[tuple[int, int]]: ...
def handleevents() -> int: ...
+1 -1
View File
@@ -67,7 +67,7 @@ release = version
# #
# This is also used if you do content translation via gettext catalogs. # This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases. # Usually you set "language" from the command line for these cases.
language = 'en' language = None
# List of patterns, relative to source directory, that match files and # List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files. # directories to ignore when looking for source files.
+76 -133
View File
@@ -10,7 +10,7 @@
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: int = PCM_PLAYBACK) ->list[str] .. function:: pcms(pcmtype=PCM_PLAYBACK)
List available PCM devices by name. List available PCM devices by name.
@@ -34,7 +34,7 @@ The :mod:`alsaaudio` module defines functions and classes for using ALSA.
*New in 0.8* *New in 0.8*
.. function:: cards() -> list[str] .. function:: cards()
List the available ALSA cards by name. This function is only moderately 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` useful. If you want to see a list of available PCM devices, use :func:`pcms`
@@ -46,7 +46,7 @@ The :mod:`alsaaudio` module defines functions and classes for using ALSA.
.. function:: card_indexes() .. function:: card_indexes()
.. function:: card_name() .. function:: card_name()
.. function:: mixers(cardindex: int = -1, device: str = 'default') -> list[str] .. function:: mixers(cardindex=-1, device='default')
List the available mixers. The arguments are: List the available mixers. The arguments are:
@@ -82,7 +82,7 @@ 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() -> str .. function:: asoundlib_version()
Return a Python string containing the ALSA version found. Return a Python string containing the ALSA version found.
@@ -96,12 +96,10 @@ 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: int = PCM_PLAYBACK, mode: int = PCM_NORMAL, rate: int = 44100, channels: int = 2, .. 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)
format: int = PCM_FORMAT_S16_LE, periodsize: int = 32, periods: int = 4,
device: str = 'default', cardindex: int = -1) -> PCM
This class is used to represent a PCM device (either for playback or This class is used to represent a PCM device (either for playback and
recording). The constructor's arguments are: recording). The arguments are:
* *type* - can be either :const:`PCM_CAPTURE` or :const:`PCM_PLAYBACK` * *type* - can be either :const:`PCM_CAPTURE` or :const:`PCM_PLAYBACK`
(default). (default).
@@ -159,15 +157,7 @@ following arguments:
**Note:** This should not be used, as it bypasses most of ALSA's configuration. **Note:** This should not be used, as it bypasses most of ALSA's configuration.
The defaults mentioned above are values passed by :mod:alsaaudio This will construct a PCM object with the given settings.
to ALSA, not anything internal to ALSA.
**Note:** For default and non-default values alike, there is no
guarantee that a PCM device supports the requested configuration,
and ALSA may pick realizable values which it believes to be closest
to the request. Therefore, after creating a PCM object, it is
necessary to verify whether its realized configuration is acceptable.
The :func:info method can be used to query it.
*Changed in 0.10:* *Changed in 0.10:*
@@ -189,27 +179,13 @@ following arguments:
PCM objects have the following methods: PCM objects have the following methods:
.. method:: PCM.info() -> dict .. method:: PCM.info()
Returns a dictionary containing the configuration of a PCM device. 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.
A small subset of properties reflects fixed parameters given by the =========================== ============================= ==================================================================
user, stored within alsaaudio. To distinguish them from properties
retrieved from ALSA when the call is made, they have their name
prefixed with **" (call value) "**.
Descriptions of properties which can be directly set during PCM object
instantiation carry the prefix "PCM():", followed by the respective
constructor parameter. Note that due to device limitations, the values
may deviate from those originally requested.
Yet another set of properties cannot be set, and derives directly from
the hardware, possibly depending on other properties. Those properties'
descriptions are prefixed with "hw:" below.
=========================== ==================================== ==================================================================
Key Description (Reference) Type Key Description (Reference) Type
=========================== ==================================== ================================================================== =========================== ============================= ==================================================================
name PCM():device string name PCM():device string
card_no *index of card* integer (negative indicates device not associable with a card) card_no *index of card* integer (negative indicates device not associable with a card)
device_no *index of PCM device* integer device_no *index of PCM device* integer
@@ -233,9 +209,7 @@ PCM objects have the following methods:
buffer_size *buffer size* integer (frames) (negative indicates error) buffer_size *buffer size* integer (frames) (negative indicates error)
get_periods *approx. periods in buffer* integer (negative indicates error) get_periods *approx. periods in buffer* integer (negative indicates error)
rate_numden *numerator, denominator* tuple (integer (Hz), integer (Hz)) rate_numden *numerator, denominator* tuple (integer (Hz), integer (Hz))
significant_bits *significant bits in sample* [#tss]_ integer (negative indicates error) significant_bits *significant bits in sample* integer (negative indicates error)
nominal_bits *nominal bits in sample* [#tss]_ integer (negative indicates error)
physical_bits *sample width in bits* [#tss]_ integer (negative indicates error)
is_batch *hw: double buffering* boolean (True: hardware supported) is_batch *hw: double buffering* boolean (True: hardware supported)
is_block_transfer *hw: block transfer* boolean (True: hardware supported) is_block_transfer *hw: block transfer* boolean (True: hardware supported)
is_double *hw: double buffering* boolean (True: hardware supported) is_double *hw: double buffering* boolean (True: hardware supported)
@@ -246,32 +220,22 @@ PCM objects have the following methods:
can_pause *hw: pause* boolean (True: hardware supported) can_pause *hw: pause* boolean (True: hardware supported)
can_resume *hw: resume* 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)
=========================== ==================================== ================================================================== =========================== ============================= ==================================================================
.. [#tss] More information in the :ref:`terminology section for sample size <term-sample-size>`
.. 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():".
The italicized descriptions give a summary of the "full" description
as can be found in the
`ALSA documentation <https://www.alsa-project.org/alsa-doc>`_.
*New in 0.9.1* .. method:: PCM.pcmtype()
.. method:: PCM.dumpinfo()
Dumps the PCM object's configured parameters to stdout.
.. method:: PCM.pcmtype() -> int
Returns the type of PCM object. Either :const:`PCM_CAPTURE` or Returns the type of PCM object. Either :const:`PCM_CAPTURE` or
:const:`PCM_PLAYBACK`. :const:`PCM_PLAYBACK`.
.. method:: PCM.pcmmode() -> int .. method:: PCM.pcmmode()
Return the mode of the PCM object. One of :const:`PCM_NONBLOCK`, Return the mode of the PCM object. One of :const:`PCM_NONBLOCK`,
:const:`PCM_ASYNC`, or :const:`PCM_NORMAL` :const:`PCM_ASYNC`, or :const:`PCM_NORMAL`
.. method:: PCM.cardname() -> string .. method:: PCM.cardname()
Return the name of the sound card used by this PCM object. Return the name of the sound card used by this PCM object.
@@ -303,23 +267,37 @@ PCM objects have the following methods:
Returns a dictionary of supported format codes (integers) keyed by Returns a dictionary of supported format codes (integers) keyed by
their standard ALSA names (strings). 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`. .. 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`. .. 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`. .. 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`. .. deprecated:: 0.9 Use the `periodsize` named argument to :func:`PCM`.
.. method:: PCM.state() -> int .. 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 Returs the current state of the stream, which can be one of
:const:`PCM_STATE_OPEN` (this should not actually happen), :const:`PCM_STATE_OPEN` (this should not actually happen),
@@ -334,21 +312,7 @@ PCM objects have the following methods:
*New in 0.10* *New in 0.10*
.. method:: PCM.avail() -> int .. method:: PCM.read()
For :const:`PCM_PLAYBACK` PCM objects, returns the number of writable
(that is, free) frames in the buffer.
For :const:`PCM_CAPTURE` PCM objects, returns the number of readable
(that is, filled) frames in the buffer.
An attempt to read/write more frames than indicated will block (in
:const:`PCM_NORMAL` mode) or fail and return zero (in
:const:`PCM_NONBLOCK` mode).
*New in 0.11*
.. method:: PCM.read() -> tuple[int, bytes]
In :const:`PCM_NORMAL` mode, this function blocks until a full period is In :const:`PCM_NORMAL` mode, this function blocks until a full period is
available, and then returns a tuple (length,data) where *length* is available, and then returns a tuple (length,data) where *length* is
@@ -360,54 +324,42 @@ PCM objects have the following methods:
``(0,'')`` if no new period has become available since the last ``(0,'')`` if no new period has become available since the last
call to read. call to read.
In case of a buffer overrun, this function will return the negative In case of an overrun, this function will return a negative size: :const:`-EPIPE`.
size :const:`-EPIPE`, and no data is read. This indicates that data was lost, even if the operation itself succeeded.
This indicates that data was lost. To resume capturing, just call read Try using a larger periodsize.
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.
.. method:: PCM.write(data: bytes) -> int .. method:: PCM.write(data)
Writes (plays) the sound in data. The length of data *must* be a 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 multiple of the frame size, and *should* be exactly the size of a
period. If less than 'period size' frames are provided, the actual period. If less than 'period size' frames are provided, the actual
playout will not happen until more data is written. playout will not happen until more data is written.
If the data was successfully written, the call returns the size of the If the device is not in :const:`PCM_NONBLOCK` mode, this call will block if
data *in frames*. 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
If the device is not in :const:`PCM_NONBLOCK` mode, this call will block size of the data provided.
if the kernel buffer is full, and until enough sound has been played
to allow the sound data to be buffered.
In :const:`PCM_NONBLOCK` mode, the call will return immediately, with a 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 return value of zero, if the buffer is full. In this case, the data
should be written again at a later time. should be written 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.
Note that this call completing means only that the samples were buffered Note that this call completing means only that the samples were buffered
in the kernel, and playout will continue afterwards. Make sure that the in the kernel, and playout will continue afterwards. Make sure that the
stream is drained before discarding the PCM handle. stream is drained before discarding the PCM handle.
.. method:: PCM.pause([enable: int = True]) -> int .. 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() -> int .. method:: PCM.drop()
Stop the stream and drop residual buffered frames. Stop the stream and drop residual buffered frames.
*New in 0.9* *New in 0.9*
.. method:: PCM.drain() -> int .. method:: PCM.drain()
For :const:`PCM_PLAYBACK` PCM objects, play residual buffered frames For :const:`PCM_PLAYBACK` PCM objects, play residual buffered frames
and then stop the stream. In :const:`PCM_NORMAL` mode, and then stop the stream. In :const:`PCM_NORMAL` mode,
@@ -417,14 +369,14 @@ PCM objects have the following methods:
*New in 0.10* *New in 0.10*
.. method:: PCM.close() -> None .. method:: PCM.close()
Closes the PCM device. Closes the PCM device.
For :const:`PCM_PLAYBACK` PCM objects in :const:`PCM_NORMAL` mode, For :const:`PCM_PLAYBACK` PCM objects in :const:`PCM_NORMAL` mode,
this function blocks until all pending playback is drained. this function blocks until all pending playback is drained.
.. method:: PCM.polldescriptors() -> list[tuple[int, int]] .. method:: PCM.polldescriptors()
Returns a list of tuples of *(file descriptor, eventmask)* that can be Returns a list of tuples of *(file descriptor, eventmask)* that can be
used to wait for changes on the PCM with *select.poll*. used to wait for changes on the PCM with *select.poll*.
@@ -432,38 +384,29 @@ PCM objects have the following methods:
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.polldescriptors_revents(descriptors: list[tuple[int, int]]) -> int .. method:: PCM.set_tstamp_mode([mode=PCM_TSTAMP_ENABLE])
Processes the descriptor list returned by :func:`polldescriptors` after
using it with *select.poll*, and returns a single *eventmask* value that
is meaningful for deciding whether :func:`read` or :func:`write` should
be called.
*New in 0.11*
.. method:: PCM.set_tstamp_mode([mode: int = PCM_TSTAMP_ENABLE])
Set the ALSA timestamp mode on the device. The mode argument can be set to 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`. 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 the integer value corresponding to the ALSA timestamp mode. The
return value can be either :const:`PCM_TSTAMP_NONE` or :const:`PCM_TSTAMP_ENABLE`. return value can be either :const:`PCM_TSTAMP_NONE` or :const:`PCM_TSTAMP_ENABLE`.
.. method:: PCM.set_tstamp_type([type: int = 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 Set the ALSA timestamp mode on the device. The type argument
can be set to either :const:`PCM_TSTAMP_TYPE_GETTIMEOFDAY`, can be set to either :const:`PCM_TSTAMP_TYPE_GETTIMEOFDAY`,
:const:`PCM_TSTAMP_TYPE_MONOTONIC` or :const:`PCM_TSTAMP_TYPE_MONOTONIC_RAW`. :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 the integer value corresponding to the ALSA timestamp type. The
return value can be either :const:`PCM_TSTAMP_TYPE_GETTIMEOFDAY`, return value can be either :const:`PCM_TSTAMP_TYPE_GETTIMEOFDAY`,
:const:`PCM_TSTAMP_TYPE_MONOTONIC` or :const:`PCM_TSTAMP_TYPE_MONOTONIC_RAW`. :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)*. Return a Python tuple *(seconds, nanoseconds, frames_available_in_buffer)*.
@@ -496,7 +439,7 @@ 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. 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 If too little data is written to the device, it will underrun, and
ugly clicking sounds will occur. Conversely, if too much data is ugly clicking sounds will occur. Conversely, of too much data is
written to the device, the write function will either block written to the device, the write function will either block
(:const:`PCM_NORMAL` mode) or return zero (:const:`PCM_NONBLOCK` mode). (:const:`PCM_NORMAL` mode) or return zero (:const:`PCM_NONBLOCK` mode).
@@ -525,7 +468,7 @@ Mixer Objects
Mixer objects provides access to the ALSA mixer API. Mixer objects provides access to the ALSA mixer API.
.. class:: Mixer(control: str = 'Master', id: int = 0, cardindex: int = -1, device: str = 'default') -> Mixer .. class:: Mixer(control='Master', id=0, cardindex=-1, device='default')
Arguments are: Arguments are:
@@ -552,20 +495,20 @@ Mixer objects provides access to the ALSA mixer API.
Mixer objects have the following methods: 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 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 Return the name of the specific mixer controlled by this object, For example
``'Master'`` or ``'PCM'`` ``'Master'`` or ``'PCM'``
.. method:: Mixer.mixerid() -> int .. 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() -> int .. 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.
Possible values in this list are: Possible values in this list are:
@@ -585,7 +528,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() -> int .. method:: Mixer.volumecap()
Returns a list of the volume control capabilities of this Returns a list of the volume control capabilities of this
mixer. Possible values in the list are: mixer. Possible values in the list are:
@@ -601,7 +544,7 @@ Mixer objects have the following methods:
'Joined Capture Volume' Manipulate sound capture volume for all channels at a time '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 For enumerated controls, return the currently selected item and the list of
items available. items available.
@@ -627,13 +570,13 @@ 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: int) -> None .. method:: Mixer.setenum(index)
For enumerated controls, sets the currently selected item. For enumerated controls, sets the currently selected item.
*index* is an index into the list of available enumerated items returned *index* is an index into the list of available enumerated items returned
by :func:`getenum`. by :func:`getenum`.
.. method:: Mixer.getrange(pcmtype: int = PCM_PLAYBACK, units: int = 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. 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 The value is a tuple of integers whose meaning is determined by the
@@ -647,7 +590,7 @@ Mixer objects have the following methods:
The optional *units* argument can be one of :const:`VOLUME_UNITS_PERCENTAGE`, The optional *units* argument can be one of :const:`VOLUME_UNITS_PERCENTAGE`,
:const:`VOLUME_UNITS_RAW`, or :const:`VOLUME_UNITS_DB`. :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 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 integers whose meaning is determined by the *units* argument.
@@ -660,7 +603,7 @@ Mixer objects have the following methods:
The optional *units* argument can be one of :const:`VOLUME_UNITS_PERCENTAGE`, The optional *units* argument can be one of :const:`VOLUME_UNITS_PERCENTAGE`,
:const:`VOLUME_UNITS_RAW`, or :const:`VOLUME_UNITS_DB`. :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) -> 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 Change the current volume settings for this mixer. The *volume* argument
is an integer whose meaning is determined by the *units* argument. is an integer whose meaning is determined by the *units* argument.
@@ -677,14 +620,14 @@ Mixer objects have the following methods:
The optional *units* argument can be one of :const:`VOLUME_UNITS_PERCENTAGE`, The optional *units* argument can be one of :const:`VOLUME_UNITS_PERCENTAGE`,
:const:`VOLUME_UNITS_RAW`, or :const:`VOLUME_UNITS_DB`. :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. Return a list indicating the current mute setting for each channel.
0 means not muted, 1 means muted. 0 means not muted, 1 means muted.
This method will fail if the mixer has no playback switch capabilities. 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 Sets the mute flag to a new value. The *mute* argument is either 0 for not
muted, or 1 for muted. muted, or 1 for muted.
@@ -694,14 +637,14 @@ 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() -> list[int] .. method:: Mixer.getrec()
Return a list indicating the current record mute setting for each channel. Return a list indicating the current record mute setting for each channel.
0 means not recording, 1 means recording. 0 means not recording, 1 means recording.
This method will fail if the mixer has no capture switch capabilities. 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 Sets the capture mute flag to a new value. The *capture* argument
is either 0 for no capture, or 1 for capture. is either 0 for no capture, or 1 for capture.
@@ -711,7 +654,7 @@ Mixer objects have the following methods:
This method will fail if the mixer has no capture switch capabilities. 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 Returns a list of tuples of *(file descriptor, eventmask)* that can be
used to wait for changes on the mixer with *select.poll*. used to wait for changes on the mixer with *select.poll*.
@@ -719,13 +662,13 @@ Mixer objects have the following methods:
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:: Mixer.handleevents() -> int .. method:: Mixer.handleevents()
Acknowledge events on the :func:`polldescriptors` file descriptors Acknowledge events on the :func:`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() -> None .. method:: Mixer.close()
Closes the Mixer device. Closes the Mixer device.
-15
View File
@@ -85,21 +85,6 @@ Period size
each write should contain exactly 32 frames of sound data, and each each write should contain exactly 32 frames of sound data, and each
read will return either 32 frames of data or nothing at all. read will return either 32 frames of data or nothing at all.
.. _term-sample-size:
Sample size
Each sample takes *physical_bits* of space. *nominal_bits* tells
how many least significant bits are used. This is the bit depth
in the format name and sometimes called just *sample bits* or
*format width*. *significant_bits* tells how many most significant
bits of the *nominal_bits* are used by the sample. This can be thought
of as the *sample resolution*. This is visualized as follows::
MSB |00000000 XXXXXXXX XXXXXXXX 00000000| LSB
|--significant--|
|---------nominal---------|
|-------------physical--------------|
Once you understand these concepts, you will be ready to use the PCM API. Read Once you understand these concepts, you will be ready to use the PCM API. Read
on. on.
+16 -19
View File
@@ -7,7 +7,6 @@
from __future__ import print_function from __future__ import print_function
import sys import sys
import time
from threading import Thread from threading import Thread
from multiprocessing import Queue from multiprocessing import Queue
@@ -16,15 +15,14 @@ if sys.version_info[0] < 3:
else: else:
from queue import Empty from queue import Empty
from math import pi, sin, ceil from math import pi, sin
import struct import struct
import itertools
import alsaaudio import alsaaudio
sampling_rate = 48000 sampling_rate = 48000
format = alsaaudio.PCM_FORMAT_S16_LE format = alsaaudio.PCM_FORMAT_S16_LE
pack_format = 'h' # short int, matching S16 framesize = 2 # bytes per frame for the values above
channels = 2 channels = 2
def nearest_frequency(frequency): def nearest_frequency(frequency):
@@ -36,28 +34,28 @@ def generate(frequency, duration = 0.125):
# generate a buffer with a sine wave of `frequency` # generate a buffer with a sine wave of `frequency`
# that is approximately `duration` seconds long # that is approximately `duration` seconds long
# the buffersize we approximately want
target_size = int(sampling_rate * channels * duration)
# the length of a full sine wave at the frequency # the length of a full sine wave at the frequency
cycle_size = int(sampling_rate / frequency) cycle_size = int(sampling_rate / frequency)
# number of full cycles we can fit into the duration # number of full cycles we can fit into target_size
factor = int(ceil(duration * frequency)) factor = int(target_size / cycle_size)
# total number of frames size = max(int(cycle_size * factor), 1)
size = cycle_size * factor
sine = [ int(32767 * sin(2 * pi * frequency * i / sampling_rate)) \ sine = [ int(32767 * sin(2 * pi * frequency * i / sampling_rate)) \
for i in range(size)] for i in range(size)]
if channels > 1: return struct.pack('%dh' % size, *sine)
sine = list(itertools.chain.from_iterable(itertools.repeat(x, channels) for x in sine))
return struct.pack(str(size * channels) + pack_format, *sine)
class SinePlayer(Thread): class SinePlayer(Thread):
def __init__(self, frequency = 440.0): def __init__(self, frequency = 440.0):
Thread.__init__(self, daemon=True) Thread.__init__(self)
self.setDaemon(True)
self.device = alsaaudio.PCM(channels=channels, format=format, rate=sampling_rate) self.device = alsaaudio.PCM(channels=channels, format=format, rate=sampling_rate)
self.queue = Queue() self.queue = Queue()
self.change(frequency) self.change(frequency)
@@ -81,17 +79,16 @@ class SinePlayer(Thread):
while True: while True:
try: try:
buffer = self.queue.get(False) buffer = self.queue.get(False)
self.device.setperiodsize(int(len(buffer) / framesize))
self.device.write(buffer)
except Empty: except Empty:
pass
if buffer: if buffer:
if self.device.write(buffer) < 0: self.device.write(buffer)
print("Playback buffer underrun! Continuing nonetheless ...")
isine = SinePlayer() isine = SinePlayer()
isine.start() isine.start()
time.sleep(1) def change(f):
isine.change(1000) isine.change(f)
time.sleep(1)
-6
View File
@@ -70,12 +70,7 @@ class Loopback(object):
self.capture = capture self.capture = capture
self.capture_pd = PollDescriptor.from_alsa_object('capture', capture) self.capture_pd = PollDescriptor.from_alsa_object('capture', capture)
self.run_after_stop = None
if run_after_stop:
self.run_after_stop = run_after_stop.split(' ') self.run_after_stop = run_after_stop.split(' ')
self.run_before_start = None
if run_before_start:
self.run_before_start = run_before_start.split(' ') self.run_before_start = run_before_start.split(' ')
self.run_after_stop_did_run = False self.run_after_stop_did_run = False
@@ -234,7 +229,6 @@ class VolumeForwarder(object):
self.playback_control = playback_control self.playback_control = playback_control
self.capture_control = capture_control self.capture_control = capture_control
self.active = True self.active = True
self.volume = None
def start(self): def start(self):
self.active = True self.active = True
+1 -2
View File
@@ -47,8 +47,7 @@ if __name__ == '__main__':
# Read data from stdin # Read data from stdin
data = f.read(320) data = f.read(320)
while data: while data:
if out.write(data) < 0: out.write(data)
print("Playback buffer underrun! Continuing nonetheless ...")
data = f.read(320) data = f.read(320)
out.close() out.close()
+1 -2
View File
@@ -39,8 +39,7 @@ def play(device, f):
data = f.readframes(periodsize) data = f.readframes(periodsize)
while data: while data:
# Read data from stdin # Read data from stdin
if device.write(data) < 0: device.write(data)
print("Playback buffer underrun! Continuing nonetheless ...")
data = f.readframes(periodsize) data = f.readframes(periodsize)
+1 -3
View File
@@ -59,8 +59,6 @@ if __name__ == '__main__':
# Read data from device # Read data from device
l, data = inp.read() l, data = inp.read()
if l < 0: if l:
print("Capture buffer overrun! Continuing nonetheless ...")
elif l:
f.write(data) f.write(data)
time.sleep(.001) time.sleep(.001)
+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.11.0' pyalsa_version = '0.10.1'
if __name__ == '__main__': if __name__ == '__main__':
setup( setup(