14 Commits

Author SHA1 Message Date
Lars Immisch
917a11b398 Report volume like alsamixer. Maybe.
I have no idea how they calculate dB.
2017-11-07 00:57:02 +01:00
Lars Immisch
ce84e69cc1 Fix kwargs, and modernize mixertest.py a bit
Preliminary error handling for dB volume settings
2017-11-06 23:32:24 +01:00
Lars Immisch
c2cfe0211b Add setting/getting volume in dB.
Potentially breaking change: getvolume now always returns a list of float values,
not integers as before.
2017-11-03 00:01:56 +01:00
Lars Immisch
bfe4899721 Merge pull request #39 from michals/master
Support 24bit audio
2017-08-30 20:52:49 +02:00
Michał Šrajer
40a1219dac Support 24bit audio
SND_PCM_FORMAT_S24_LE and similar are for 24bit ints packed in 4-bytes each.
There is a similar family of formats for 3-bytes packed data (as stored in 24bit wave files).

This commit:
 - adds S24_3LE, S24_3BE, U24_3LE, U24_3BE PCM formats to the alsaaudio.c
 - updates documentation
 - updates playwav.py to correctly play typical 24Bit PCM wave files

Closes #38
2017-08-29 19:09:54 +02:00
Lars Immisch
54e2712b7a Document release procedure 2017-07-09 15:01:41 +02:00
Lars Immisch
f9685e0b30 Correct capitalization
as suggested by Ben Loveridge
2017-07-09 13:32:08 +02:00
Lars Immisch
b4a670c50d Doc fixes. 2017-03-31 00:29:19 +02:00
Lars Immisch
370a4b6249 Regenerated doc. 2017-03-31 00:25:00 +02:00
Lars Immisch
eca217dff9 Document PCM.polldescriptors.
Closes #32
2017-03-30 23:20:22 +02:00
Lars Immisch
65d3c4a283 Typo. 2017-03-17 20:42:02 +01:00
Lars Immisch
adc0d800e1 Document EPIPE 2017-03-17 20:40:40 +01:00
Lars Immisch
02cf16d10d Improve documentation 2017-02-25 01:32:54 +01:00
Lars Immisch
94ced0517e Correct the sine example (finally!) Closes #10 2017-02-25 01:04:18 +01:00
10 changed files with 386 additions and 248 deletions

11
NOTES.md Normal file
View File

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

View File

@@ -77,6 +77,12 @@ typedef struct {
snd_mixer_t *handle;
} alsamixer_t;
typedef enum {
unit_percent,
unit_dB,
unit_last
} volume_unit_t;
/******************************************/
/* PCM object wrapper */
/******************************************/
@@ -1567,21 +1573,31 @@ Possible values in this list are:\n\
- 'Capture Exclusive'\n");
static int alsamixer_getpercentage(long min, long max, long value)
static double alsamixer_getpercentage(long min, long max, long value)
{
/* Convert from number in range to percentage */
int range = max - min;
int tmp;
if (range == 0)
return 0;
value -= min;
tmp = rint((double)value/(double)range * 100);
return tmp;
return (double)value/(double)range * 100.0;
}
static long alsamixer_getphysvolume(long min, long max, int percentage)
static double alsamixer_getdB(long min, long max, long value)
{
/* Convert from number in range to dB */
int range = max - min;
if (range == 0)
return 0;
value -= min;
return log10((double)value/range) * 60.0;
}
static long alsamixer_getphysvolume(long min, long max, double percentage)
{
/* Convert from percentage to number in range */
int range = max - min;
@@ -1590,57 +1606,76 @@ static long alsamixer_getphysvolume(long min, long max, int percentage)
if (range == 0)
return 0;
tmp = rint((double)range * ((double)percentage*.01)) + min;
tmp = rint((double)range * (percentage * .01)) + min;
return tmp;
}
static PyObject *
alsamixer_getvolume(alsamixer_t *self, PyObject *args)
alsamixer_getvolume(alsamixer_t *self, PyObject *args, PyObject *kw)
{
snd_mixer_elem_t *elem;
int channel;
long ival;
PyObject *pcmtypeobj = NULL;
long pcmtype;
PyObject *dirobj = NULL;
long dir;
int unit = unit_percent;
PyObject *result;
PyObject *item;
if (!PyArg_ParseTuple(args,"|O:getvolume", &pcmtypeobj))
static char *kwlist[] = { "direction", "unit", NULL };
if (!PyArg_ParseTupleAndKeywords(args, kw, "|Oi:getvolume", kwlist, &dirobj, &unit))
return NULL;
if (unit >= unit_last) {
PyErr_SetString(PyExc_ValueError, "unit must be 'percent' or 'dB'");
return NULL;
}
dir = get_pcmtype(dirobj);
if (dir < 0) {
return NULL;
}
if (!self->handle)
{
PyErr_SetString(ALSAAudioError, "Mixer is closed");
return NULL;
}
pcmtype = get_pcmtype(pcmtypeobj);
if (pcmtype < 0) {
return NULL;
}
elem = alsamixer_find_elem(self->handle,self->controlname,self->controlid);
result = PyList_New(0);
for (channel = 0; channel <= SND_MIXER_SCHN_LAST; channel++) {
if (pcmtype == SND_PCM_STREAM_PLAYBACK &&
if (dir == SND_PCM_STREAM_PLAYBACK &&
snd_mixer_selem_has_playback_channel(elem, channel))
{
snd_mixer_selem_get_playback_volume(elem, channel, &ival);
item = PyLong_FromLong(alsamixer_getpercentage(self->pmin,
self->pmax,
ival));
if (unit == unit_percent) {
item = PyFloat_FromDouble(
alsamixer_getpercentage(self->pmin, self->pmax, ival));
}
else {
item = PyFloat_FromDouble(
alsamixer_getdB(self->pmin, self->pmax, ival));
}
PyList_Append(result, item);
Py_DECREF(item);
}
else if (pcmtype == SND_PCM_STREAM_CAPTURE
else if (dir == SND_PCM_STREAM_CAPTURE
&& snd_mixer_selem_has_capture_channel(elem, channel)
&& snd_mixer_selem_has_capture_volume(elem)) {
&& snd_mixer_selem_has_capture_volume(elem))
{
snd_mixer_selem_get_capture_volume(elem, channel, &ival);
item = PyLong_FromLong(alsamixer_getpercentage(self->cmin,
self->cmax,
ival));
if (unit == unit_percent) {
item = PyFloat_FromDouble(
alsamixer_getpercentage(self->cmin, self->cmax, ival));
}
else {
item = PyFloat_FromDouble(
alsamixer_getdB(self->cmin, self->cmax, ival));
}
PyList_Append(result, item);
Py_DECREF(item);
}
@@ -1650,15 +1685,17 @@ alsamixer_getvolume(alsamixer_t *self, PyObject *args)
}
PyDoc_STRVAR(getvolume_doc,
"getvolume([pcmtype]) -> List of volume settings (int)\n\
"getvolume(direction=PCM_PLAYBACK, unit=Percent) -> List of volume settings (float)\n\
\n\
Returns a list with the current volume settings for each channel.\n\
The list elements are integer percentages.\n\
The list elements are float percentages.\n\
\n\
The optional 'pcmtype' argument can be either PCM_PLAYBACK or\n\
The 'direction' argument can be either PCM_PLAYBACK or\n\
PCM_CAPTURE, which is relevant if the mixer can control both\n\
playback and capture volume. The default value is PCM_PLAYBACK\n\
if the mixer has this capability, otherwise PCM_CAPTURE");
if the mixer has this capability, otherwise PCM_CAPTURE\
\n\
The optional 'unit' argument can be either 'percent' or 'dB'.");
static PyObject *
@@ -1984,29 +2021,53 @@ This method will fail if the mixer has no capture switch capabilities.");
static PyObject *
alsamixer_setvolume(alsamixer_t *self, PyObject *args)
alsamixer_setvolume(alsamixer_t *self, PyObject *args, PyObject *kw)
{
snd_mixer_elem_t *elem;
int i;
long volume;
double volume = 0.0;
PyObject *volumeobj = NULL;
int physvolume;
PyObject *pcmtypeobj = NULL;
long pcmtype;
PyObject *dirobj = NULL;
long dir;
int unit = unit_percent;
int channel = MIXER_CHANNEL_ALL;
int done = 0;
if (!PyArg_ParseTuple(args,"l|iO:setvolume", &volume, &channel,
&pcmtypeobj))
return NULL;
if (volume < 0 || volume > 100)
{
PyErr_SetString(ALSAAudioError, "Volume must be between 0 and 100");
static char *kwlist[] = { "channel", "direction", "unit", NULL };
if (!PyArg_ParseTupleAndKeywords(args, kw, "O|iOi:setvolume", kwlist, &volumeobj, &channel,
&dirobj, &unit)) {
return NULL;
}
pcmtype = get_pcmtype(pcmtypeobj);
if (pcmtype < 0) {
// unit
if (unit >= unit_last) {
PyErr_SetString(PyExc_ValueError, "unit must be 'percent' or 'dB'");
return NULL;
}
if (PyLong_Check(volumeobj)) {
volume = (double)PyLong_AsLong(volumeobj);
}
else if (PyFloat_Check(volumeobj)) {
volume = PyFloat_AsDouble(volumeobj);
}
else {
PyErr_SetString(PyExc_ValueError, "Volume must be integer or float");
return NULL;
}
if (unit == unit_percent && (volume < 0.0 || volume > 100.0))
{
PyErr_SetString(PyExc_ValueError, "Volume in percent must be between 0 and 100");
return NULL;
}
// pcmtype
dir = get_pcmtype(dirobj);
if (dir < 0) {
return NULL;
}
@@ -2015,41 +2076,51 @@ alsamixer_setvolume(alsamixer_t *self, PyObject *args)
PyErr_SetString(ALSAAudioError, "Mixer is closed");
return NULL;
}
elem = alsamixer_find_elem(self->handle,self->controlname,self->controlid);
if (!pcmtypeobj || (pcmtypeobj == Py_None))
if (!dirobj || (dirobj == Py_None))
{
if (self->pchannels)
pcmtype = SND_PCM_STREAM_PLAYBACK;
dir = SND_PCM_STREAM_PLAYBACK;
else
pcmtype = SND_PCM_STREAM_CAPTURE;
dir = SND_PCM_STREAM_CAPTURE;
}
for (i = 0; i <= SND_MIXER_SCHN_LAST; i++)
{
if (channel == -1 || channel == i)
{
if (pcmtype == SND_PCM_STREAM_PLAYBACK &&
if (dir == SND_PCM_STREAM_PLAYBACK &&
snd_mixer_selem_has_playback_channel(elem, i)) {
physvolume = alsamixer_getphysvolume(self->pmin,
self->pmax, volume);
snd_mixer_selem_set_playback_volume(elem, i, physvolume);
if (unit == unit_percent) {
physvolume = alsamixer_getphysvolume(self->pmin,
self->pmax, volume);
snd_mixer_selem_set_playback_volume(elem, i, physvolume);
}
else {
snd_mixer_selem_set_playback_dB(elem, i, (long)(volume * 100.0), 0);
}
done++;
}
else if (pcmtype == SND_PCM_STREAM_CAPTURE
else if (dir == SND_PCM_STREAM_CAPTURE
&& snd_mixer_selem_has_capture_channel(elem, i)
&& snd_mixer_selem_has_capture_volume(elem))
{
physvolume = alsamixer_getphysvolume(self->cmin, self->cmax,
volume);
snd_mixer_selem_set_capture_volume(elem, i, physvolume);
if (unit == unit_percent) {
physvolume = alsamixer_getphysvolume(self->cmin, self->cmax,
volume);
snd_mixer_selem_set_capture_volume(elem, i, physvolume);
}
else {
snd_mixer_selem_set_capture_dB(elem, i, (long)(volume * 100), 0);
}
done++;
}
}
}
if(!done)
if (!done)
{
PyErr_Format(ALSAAudioError, "No such channel [%s]",
self->cardname);
@@ -2061,19 +2132,21 @@ alsamixer_setvolume(alsamixer_t *self, PyObject *args)
}
PyDoc_STRVAR(setvolume_doc,
"setvolume(volume[[, channel] [, pcmtype]])\n\
"setvolume(volume, channel=MIXER_CHANNEL_ALL, direction=PCM_PLAYBACK, unit='percent')\n\
\n\
Change the current volume settings for this mixer. The volume argument\n\
controls the new volume setting as an integer percentage.\n\
controls the new volume setting as a percentage.\n\
If the optional argument channel is present, the volume is set only for\n\
this channel. This assumes that the mixer can control the volume for the\n\
channels independently.\n\
\n\
The optional direction argument can be either PCM_PLAYBACK or PCM_CAPTURE.\n\
The optional 'direction' argument can be either PCM_PLAYBACK or PCM_CAPTURE.\n\
It is relevant if the mixer has independent playback and capture volume\n\
capabilities, and controls which of the volumes will be changed.\n\
The default is 'playback' if the mixer has this capability, otherwise\n\
'capture'.");
The default is PCM_PLAYBACK if the mixer has this capability, otherwise\n\
PCM_CAPTURE.\n\
\n\
The optional 'unit' argument can be either 'percent' (the default) or 'dB'.");
static PyObject *
@@ -2084,6 +2157,7 @@ alsamixer_setmute(alsamixer_t *self, PyObject *args)
int mute = 0;
int done = 0;
int channel = MIXER_CHANNEL_ALL;
if (!PyArg_ParseTuple(args,"i|i:setmute", &mute, &channel))
return NULL;
@@ -2291,13 +2365,13 @@ static PyMethodDef alsamixer_methods[] = {
switchcap_doc},
{"volumecap", (PyCFunction)alsamixer_volumecap, METH_VARARGS,
volumecap_doc},
{"getvolume", (PyCFunction)alsamixer_getvolume, METH_VARARGS,
{"getvolume", (PyCFunction)alsamixer_getvolume, METH_VARARGS | METH_KEYWORDS,
getvolume_doc},
{"getrange", (PyCFunction)alsamixer_getrange, METH_VARARGS, getrange_doc},
{"getenum", (PyCFunction)alsamixer_getenum, METH_VARARGS, getenum_doc},
{"getmute", (PyCFunction)alsamixer_getmute, METH_VARARGS, getmute_doc},
{"getrec", (PyCFunction)alsamixer_getrec, METH_VARARGS, getrec_doc},
{"setvolume", (PyCFunction)alsamixer_setvolume, METH_VARARGS,
{"setvolume", (PyCFunction)alsamixer_setvolume, METH_VARARGS | METH_KEYWORDS,
setvolume_doc},
{"setenum", (PyCFunction)alsamixer_setenum, METH_VARARGS, setenum_doc},
{"setmute", (PyCFunction)alsamixer_setmute, METH_VARARGS, setmute_doc},
@@ -2447,6 +2521,9 @@ PyObject *PyInit_alsaaudio(void)
Py_INCREF(ALSAAudioError);
PyModule_AddObject(m, "ALSAAudioError", ALSAAudioError);
_EXPORT_INT(m, "Percent", unit_percent);
_EXPORT_INT(m, "dB", unit_dB);
_EXPORT_INT(m, "PCM_PLAYBACK",SND_PCM_STREAM_PLAYBACK);
_EXPORT_INT(m, "PCM_CAPTURE",SND_PCM_STREAM_CAPTURE);
@@ -2478,6 +2555,10 @@ PyObject *PyInit_alsaaudio(void)
_EXPORT_INT(m, "PCM_FORMAT_IMA_ADPCM",SND_PCM_FORMAT_IMA_ADPCM);
_EXPORT_INT(m, "PCM_FORMAT_MPEG",SND_PCM_FORMAT_MPEG);
_EXPORT_INT(m, "PCM_FORMAT_GSM",SND_PCM_FORMAT_GSM);
_EXPORT_INT(m, "PCM_FORMAT_S24_3LE",SND_PCM_FORMAT_S24_3LE);
_EXPORT_INT(m, "PCM_FORMAT_S24_3BE",SND_PCM_FORMAT_S24_3BE);
_EXPORT_INT(m, "PCM_FORMAT_U24_3LE",SND_PCM_FORMAT_U24_3LE);
_EXPORT_INT(m, "PCM_FORMAT_U24_3BE",SND_PCM_FORMAT_U24_3BE);
/* DSD sample formats are included in ALSA 1.0.29 and higher
* define OVERRIDE_DSD_COMPILE to include DSD sample support

View File

@@ -1,182 +1,160 @@
# -*- coding: utf-8 -*-
#
# alsaaudio documentation build configuration file, created by
# sphinx-quickstart on Sat Nov 22 00:17:09 2008.
# alsaaudio documentation documentation build configuration file, created by
# sphinx-quickstart on Thu Mar 30 23:52:21 2017.
#
# This file is execfile()d with the current directory set to its containing dir.
# This file is execfile()d with the current directory set to its
# containing dir.
#
# The contents of this file are pickled, so don't put values in the namespace
# that aren't pickleable (module imports are okay, they're removed automatically).
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default value; values that are commented out
# serve to show the default value.
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
import sys
sys.path.insert(0, '..')
from setup import pyalsa_version
# If your extensions are in another directory, add it here. If the directory
# is relative to the documentation root, use os.path.abspath to make it
# absolute, like shown here.
#sys.path.append(os.path.abspath('some/directory'))
# General configuration
# ---------------------
# -- General configuration ------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = []
# Add any paths that contain templates here, relative to this directory.
templates_path = ['.templates']
templates_path = ['_templates']
# The suffix of source filenames.
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General substitutions.
project = u'alsaaudio'
copyright = u'2008-20017, Casper Wilstrup, Lars Immisch'
# General information about the project.
project = u'alsaaudio documentation'
copyright = u'2017, Lars Immisch & Casper Wilstrup'
author = u'Lars Immisch & Casper Wilstrup'
# The default replacements for |version| and |release|, also used in various
# other places throughout the built documents.
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = pyalsa_version
# The full version, including alpha/beta/rc tags.
release = pyalsa_version
release = version
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
today_fmt = '%B %d, %Y'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of documents that shouldn't be included in the build.
#unused_docs = []
# List of directories, relative to source directories, that shouldn't be searched
# for source files.
exclude_trees = ['.build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# Options for HTML output
# -----------------------
# The style sheet to use for HTML and HTML Help pages. A file of that name
# must exist either in Sphinx' static/ path, or in one of the custom paths
# given in html_static_path.
html_style = 'default.css'
# -- Options for HTML output ----------------------------------------------
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['static']
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_use_modindex = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, the reST sources are included in the HTML build as _sources/<name>.
#html_copy_source = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'alsaaudiodoc'
htmlhelp_basename = 'alsaaudiodocumentationdoc'
# Options for LaTeX output
# ------------------------
# -- Options for LaTeX output ---------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, document class [howto/manual]).
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
('index', 'alsaaudio.tex', u'alsaaudio Documentation',
u'Casper Wilstrup, Lars Immisch', 'manual'),
(master_doc, 'alsaaudiodocumentation.tex', u'alsaaudio documentation Documentation',
u'Lars Immisch', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'alsaaudiodocumentation', u'alsaaudio documentation Documentation',
[author], 1)
]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'alsaaudiodocumentation', u'alsaaudio documentation Documentation',
author, 'alsaaudiodocumentation', 'One line description of project.',
'Miscellaneous'),
]
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_use_modindex = True

View File

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

View File

@@ -193,10 +193,10 @@ PCM objects have the following methods:
``PCM_FORMAT_S16_BE`` Signed 16 bit samples for each channel (Big Endian byte order)
``PCM_FORMAT_U16_LE`` Unsigned 16 bit samples for each channel (Little Endian byte order)
``PCM_FORMAT_U16_BE`` Unsigned 16 bit samples for each channel (Big Endian byte order)
``PCM_FORMAT_S24_LE`` Signed 24 bit samples for each channel (Little Endian byte order)
``PCM_FORMAT_S24_BE`` Signed 24 bit samples for each channel (Big Endian byte order)}
``PCM_FORMAT_U24_LE`` Unsigned 24 bit samples for each channel (Little Endian byte order)
``PCM_FORMAT_U24_BE`` Unsigned 24 bit samples for each channel (Big Endian byte order)
``PCM_FORMAT_S24_LE`` Signed 24 bit samples for each channel (Little Endian byte order in 4 bytes)
``PCM_FORMAT_S24_BE`` Signed 24 bit samples for each channel (Big Endian byte order in 4 bytes)
``PCM_FORMAT_U24_LE`` Unsigned 24 bit samples for each channel (Little Endian byte order in 4 bytes)
``PCM_FORMAT_U24_BE`` Unsigned 24 bit samples for each channel (Big Endian byte order in 4 bytes)
``PCM_FORMAT_S32_LE`` Signed 32 bit samples for each channel (Little Endian byte order)
``PCM_FORMAT_S32_BE`` Signed 32 bit samples for each channel (Big Endian byte order)
``PCM_FORMAT_U32_LE`` Unsigned 32 bit samples for each channel (Little Endian byte order)
@@ -210,6 +210,10 @@ PCM objects have the following methods:
``PCM_FORMAT_IMA_ADPCM`` A 4:1 compressed format defined by the Interactive Multimedia Association.
``PCM_FORMAT_MPEG`` MPEG encoded audio?
``PCM_FORMAT_GSM`` 9600 bits/s constant rate encoding for speech
``PCM_FORMAT_S24_3LE`` Signed 24 bit samples for each channel (Little Endian byte order in 3 bytes)
``PCM_FORMAT_S24_3BE`` Signed 24 bit samples for each channel (Big Endian byte order in 3 bytes)
``PCM_FORMAT_U24_3LE`` Unsigned 24 bit samples for each channel (Little Endian byte order in 3 bytes)
``PCM_FORMAT_U24_3BE`` Unsigned 24 bit samples for each channel (Big Endian byte order in 3 bytes)
========================= ===============
@@ -233,6 +237,9 @@ PCM objects have the following methods:
``(0,'')`` if no new period has become available since the last
call to read.
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)
@@ -256,6 +263,17 @@ PCM objects have the following methods:
If *enable* is :const:`True`, playback or capture is paused.
Otherwise, playback/capture is resumed.
.. method:: PCM.polldescriptors()
Returns a tuple of *(file descriptor, eventmask)* that can be used to
wait for changes on the mixer with *select.poll*.
The *eventmask* value is compatible with `poll.register`__ in the Python
:const:`select` module.
__ poll_objects_
**A few hints on using PCM devices for playback**
The most common reason for problems with playback of PCM audio is that writes
@@ -425,31 +443,35 @@ Mixer objects have the following methods:
This method will fail if the mixer has no capture switch capabilities.
.. method:: Mixer.getvolume([direction])
.. method:: Mixer.getvolume(direction=PCM_PLAYBACK, unit=Percent)
Returns a list with the current volume settings for each channel. The list
elements are integer percentages.
elements are percentages or dB values, depending on *unit*.
The optional *direction* argument can be either :const:`PCM_PLAYBACK` or
The *direction* argument can be either :const:`PCM_PLAYBACK` or
:const:`PCM_CAPTURE`, which is relevant if the mixer can control both
playback and capture volume. The default value is :const:`PCM_PLAYBACK`
if the mixer has playback channels, otherwise it is :const:`PCM_CAPTURE`.
.. method:: Mixer.setvolume(volume, [channel], [direction])
.. method:: Mixer.setvolume(volume, channel=MIXER_CHANNEL_ALL, direction=PCM_PLAYBACK, unit=Percent)
Change the current volume settings for this mixer. The *volume* argument
controls the new volume setting as an integer percentage.
controls the new volume setting as either a percentage or a dB value. Both
integer and floating point values can be given.
If the optional argument *channel* is present, the volume is set
only for this channel. This assumes that the mixer can control the
volume for the channels independently.
The *channel* argument can be used to restrict the channels for which the volume is
set. By default, the volume of all channels is adjusted. This assumes that the mixer
can control the volume for the channels independently.
The optional *direction* argument can be either :const:`PCM_PLAYBACK` or
The *direction* argument can be either :const:`PCM_PLAYBACK` or
:const:`PCM_CAPTURE`, which is relevant if the mixer can control both
playback and capture volume. The default value is :const:`PCM_PLAYBACK`
if the mixer has playback channels, otherwise it is :const:`PCM_CAPTURE`.
The *unit* argument determines how the volume value is interpreted, as a prcentage
or as a dB value.
.. method:: Mixer.setmute(mute, [channel])
Sets the mute flag to a new value. The *mute* argument is either 0 for not
@@ -473,9 +495,14 @@ Mixer objects have the following methods:
.. method:: Mixer.polldescriptors()
Returns a tuple of (file descriptor, eventmask) that can be used to
Returns a tuple of *(file descriptor, eventmask)* that can be used to
wait for changes on the mixer with *select.poll*.
The *eventmask* value is compatible with `poll.register`__ in the Python
:const:`select` module.
__ poll_objects_
.. method:: Mixer.handleevents()
Acknowledge events on the *polldescriptors* file descriptors
@@ -620,3 +647,5 @@ argument::
.. rubric:: Footnotes
.. [#f1] ALSA also allows ``PCM_ASYNC``, but this is not supported yet.
.. _poll_objects: http://docs.python.org/library/select.html#poll-objects

View File

@@ -110,25 +110,32 @@ And then as root: --- ::
Testing
*******
First of all, run::
$ python test.py
Make sure that :code:`aplay` plays a file through the soundcard you want, then
try::
This is a small test suite that mostly performs consistency tests. If
it fails, please file a `bug report
<https://github.com/larsimmisch/pyalsaaudio/issues>`_.
$ python playwav.py <filename.wav>
If :code:`aplay` needs a device argument, like
:code:`aplay -D hw:CARD=sndrpihifiberry,DEV=0`, use::
$ python playwav.py -d hw:CARD=sndrpihifiberry,DEV=0 <filename.wav>
To test PCM recordings (on your default soundcard), verify your
microphone works, then do::
$ python recordtest.py <filename>
$ python recordtest.py -d <device> <filename>
Speak into the microphone, and interrupt the recording at any time
with ``Ctl-C``.
Play back the recording with::
$ python playbacktest.py <filename>
$ python playbacktest.py-d <device> <filename>
There is a minimal test suite in :code:`test.py`, but it is
a bit dependent on the ALSA configuration and may fail without indicating
a real problem.
If you find bugs/problems, please file a `bug report
<https://github.com/larsimmisch/pyalsaaudio/issues>`_.

View File

@@ -46,7 +46,7 @@ Data rate
At the other end of the scale, 96000 Hz, 6 channel sound with 64
bit (8 bytes) samples has a data rate of 96000 \* 6 \* 8 = 4608
kb/s (almost 5 Mb sound data per second)
kb/s (almost 5 MB sound data per second)
Period
When the hardware processes data this is done in chunks of frames. The time

View File

@@ -6,30 +6,50 @@
from __future__ import print_function
import sys
from threading import Thread
from queue import Queue, Empty
from multiprocessing import Queue
if sys.version_info[0] < 3:
from Queue import Empty
else:
from queue import Empty
from math import pi, sin
import struct
import alsaaudio
sampling_rate = 44100
sampling_rate = 48000
format = alsaaudio.PCM_FORMAT_S16_LE
framesize = 2 # bytes per frame for the values above
channels = 2
def digitize(s):
if s > 1.0 or s < -1.0:
raise ValueError
return struct.pack('h', int(s * 32767))
def nearest_frequency(frequency):
# calculate the nearest frequency where the wave form fits into the buffer
# in other words, select f so that sampling_rate/f is an integer
return float(sampling_rate)/int(sampling_rate/frequency)
def generate(frequency):
# generate a buffer with a sine wave of frequency
size = int(sampling_rate / frequency)
buffer = bytes()
for i in range(size):
buffer = buffer + digitize(sin(i/(2 * pi)))
def generate(frequency, duration = 0.125):
# generate a buffer with a sine wave of `frequency`
# that is approximately `duration` seconds long
return buffer
# the buffersize we approximately want
target_size = int(sampling_rate * channels * duration)
# the length of a full sine wave at the frequency
cycle_size = int(sampling_rate / frequency)
# number of full cycles we can fit into target_size
factor = int(target_size / cycle_size)
size = max(int(cycle_size * factor), 1)
sine = [ int(32767 * sin(2 * pi * frequency * i / sampling_rate)) \
for i in range(size)]
return struct.pack('%dh' % size, *sine)
class SinePlayer(Thread):
@@ -37,7 +57,7 @@ class SinePlayer(Thread):
Thread.__init__(self)
self.setDaemon(True)
self.device = alsaaudio.PCM()
self.device.setchannels(1)
self.device.setchannels(channels)
self.device.setformat(format)
self.device.setrate(sampling_rate)
self.queue = Queue()
@@ -47,19 +67,15 @@ class SinePlayer(Thread):
'''This is called outside of the player thread'''
# we generate the buffer in the calling thread for less
# latency when switching frequencies
# More than 100 writes/s are pushing it - play multiple buffers
# for higher frequencies
if frequency > sampling_rate / 2:
raise ValueError('maximum frequency is %d' % (sampling_rate / 2))
factor = int(frequency/100.0)
if factor == 0:
factor = 1
buf = generate(frequency) * factor
print('factor: %d, frames: %d' % (factor, len(buf) / framesize))
f = nearest_frequency(frequency)
print('nearest frequency: %f' % f)
self.queue.put( buf)
buf = generate(f)
self.queue.put(buf)
def run(self):
buffer = None

View File

@@ -46,13 +46,17 @@ def show_mixer(name, kwargs):
print("Capabilities: %s %s" % (' '.join(mixer.volumecap()),
' '.join(mixer.switchcap())))
volumes = mixer.getvolume()
for i in range(len(volumes)):
print("Channel %i volume: %i%%" % (i,volumes[i]))
for i, v in enumerate(volumes):
print("Channel %i volume: %.02f%%" % (i, v))
volumes = mixer.getvolume(unit=alsaaudio.dB)
for i, v in enumerate(volumes):
print("Channel %i volume: %.02fdB" % (i, v))
try:
mutes = mixer.getmute()
for i in range(len(mutes)):
if mutes[i]:
for i, m in enumerate(mutes):
if m:
print("Channel %i is muted" % i)
except alsaaudio.ALSAAudioError:
# May not support muting
@@ -60,8 +64,8 @@ def show_mixer(name, kwargs):
try:
recs = mixer.getrec()
for i in range(len(recs)):
if recs[i]:
for i, r in enumerate(recs):
if r:
print("Channel %i is recording" % i)
except alsaaudio.ALSAAudioError:
# May not support recording

View File

@@ -24,7 +24,7 @@ def play(device, f):
elif f.getsampwidth() == 2:
device.setformat(alsaaudio.PCM_FORMAT_S16_LE)
elif f.getsampwidth() == 3:
device.setformat(alsaaudio.PCM_FORMAT_S24_LE)
device.setformat(alsaaudio.PCM_FORMAT_S24_3LE)
elif f.getsampwidth() == 4:
device.setformat(alsaaudio.PCM_FORMAT_S32_LE)
else: