]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/python/contrib/Doc/library/ossaudiodev.rst
Inital import
[l4.git] / l4 / pkg / python / contrib / Doc / library / ossaudiodev.rst
1
2 :mod:`ossaudiodev` --- Access to OSS-compatible audio devices
3 =============================================================
4
5 .. module:: ossaudiodev
6    :platform: Linux, FreeBSD
7    :synopsis: Access to OSS-compatible audio devices.
8
9
10 .. versionadded:: 2.3
11
12 This module allows you to access the OSS (Open Sound System) audio interface.
13 OSS is available for a wide range of open-source and commercial Unices, and is
14 the standard audio interface for Linux and recent versions of FreeBSD.
15
16 .. Things will get more complicated for future Linux versions, since
17    ALSA is in the standard kernel as of 2.5.x.  Presumably if you
18    use ALSA, you'll have to make sure its OSS compatibility layer
19    is active to use ossaudiodev, but you're gonna need it for the vast
20    majority of Linux audio apps anyways.
21
22    Sounds like things are also complicated for other BSDs.  In response
23    to my python-dev query, Thomas Wouters said:
24
25    > Likewise, googling shows OpenBSD also uses OSS/Free -- the commercial
26    > OSS installation manual tells you to remove references to OSS/Free from the
27    > kernel :)
28
29    but Aleksander Piotrowsk actually has an OpenBSD box, and he quotes
30    from its <soundcard.h>:
31    >  * WARNING!  WARNING!
32    >  * This is an OSS (Linux) audio emulator.
33    >  * Use the Native NetBSD API for developing new code, and this
34    >  * only for compiling Linux programs.
35
36    There's also an ossaudio manpage on OpenBSD that explains things
37    further.  Presumably NetBSD and OpenBSD have a different standard
38    audio interface.  That's the great thing about standards, there are so
39    many to choose from ... ;-)
40
41    This probably all warrants a footnote or two, but I don't understand
42    things well enough right now to write it!   --GPW
43
44
45 .. seealso::
46
47    `Open Sound System Programmer's Guide <http://www.opensound.com/pguide/oss.pdf>`_
48       the official documentation for the OSS C API
49
50    The module defines a large number of constants supplied by the OSS device
51    driver; see ``<sys/soundcard.h>`` on either Linux or FreeBSD for a listing .
52
53 :mod:`ossaudiodev` defines the following variables and functions:
54
55
56 .. exception:: OSSAudioError
57
58    This exception is raised on certain errors.  The argument is a string describing
59    what went wrong.
60
61    (If :mod:`ossaudiodev` receives an error from a system call such as
62    :cfunc:`open`, :cfunc:`write`, or :cfunc:`ioctl`, it raises :exc:`IOError`.
63    Errors detected directly by :mod:`ossaudiodev` result in :exc:`OSSAudioError`.)
64
65    (For backwards compatibility, the exception class is also available as
66    ``ossaudiodev.error``.)
67
68
69 .. function:: open([device, ]mode)
70
71    Open an audio device and return an OSS audio device object.  This object
72    supports many file-like methods, such as :meth:`read`, :meth:`write`, and
73    :meth:`fileno` (although there are subtle differences between conventional Unix
74    read/write semantics and those of OSS audio devices).  It also supports a number
75    of audio-specific methods; see below for the complete list of methods.
76
77    *device* is the audio device filename to use.  If it is not specified, this
78    module first looks in the environment variable :envvar:`AUDIODEV` for a device
79    to use.  If not found, it falls back to :file:`/dev/dsp`.
80
81    *mode* is one of ``'r'`` for read-only (record) access, ``'w'`` for
82    write-only (playback) access and ``'rw'`` for both. Since many sound cards
83    only allow one process to have the recorder or player open at a time, it is a
84    good idea to open the device only for the activity needed.  Further, some
85    sound cards are half-duplex: they can be opened for reading or writing, but
86    not both at once.
87
88    Note the unusual calling syntax: the *first* argument is optional, and the
89    second is required.  This is a historical artifact for compatibility with the
90    older :mod:`linuxaudiodev` module which :mod:`ossaudiodev` supersedes.
91
92    .. XXX it might also be motivated
93       by my unfounded-but-still-possibly-true belief that the default
94       audio device varies unpredictably across operating systems.  -GW
95
96
97 .. function:: openmixer([device])
98
99    Open a mixer device and return an OSS mixer device object.   *device* is the
100    mixer device filename to use.  If it is not specified, this module first looks
101    in the environment variable :envvar:`MIXERDEV` for a device to use.  If not
102    found, it falls back to :file:`/dev/mixer`.
103
104
105 .. _ossaudio-device-objects:
106
107 Audio Device Objects
108 --------------------
109
110 Before you can write to or read from an audio device, you must call three
111 methods in the correct order:
112
113 #. :meth:`setfmt` to set the output format
114
115 #. :meth:`channels` to set the number of channels
116
117 #. :meth:`speed` to set the sample rate
118
119 Alternately, you can use the :meth:`setparameters` method to set all three audio
120 parameters at once.  This is more convenient, but may not be as flexible in all
121 cases.
122
123 The audio device objects returned by :func:`open` define the following methods
124 and (read-only) attributes:
125
126
127 .. method:: oss_audio_device.close()
128
129    Explicitly close the audio device.  When you are done writing to or reading from
130    an audio device, you should explicitly close it.  A closed device cannot be used
131    again.
132
133
134 .. method:: oss_audio_device.fileno()
135
136    Return the file descriptor associated with the device.
137
138
139 .. method:: oss_audio_device.read(size)
140
141    Read *size* bytes from the audio input and return them as a Python string.
142    Unlike most Unix device drivers, OSS audio devices in blocking mode (the
143    default) will block :func:`read` until the entire requested amount of data is
144    available.
145
146
147 .. method:: oss_audio_device.write(data)
148
149    Write the Python string *data* to the audio device and return the number of
150    bytes written.  If the audio device is in blocking mode (the default), the
151    entire string is always written (again, this is different from usual Unix device
152    semantics).  If the device is in non-blocking mode, some data may not be written
153    ---see :meth:`writeall`.
154
155
156 .. method:: oss_audio_device.writeall(data)
157
158    Write the entire Python string *data* to the audio device: waits until the audio
159    device is able to accept data, writes as much data as it will accept, and
160    repeats until *data* has been completely written. If the device is in blocking
161    mode (the default), this has the same effect as :meth:`write`; :meth:`writeall`
162    is only useful in non-blocking mode.  Has no return value, since the amount of
163    data written is always equal to the amount of data supplied.
164
165 The following methods each map to exactly one :func:`ioctl` system call.  The
166 correspondence is obvious: for example, :meth:`setfmt` corresponds to the
167 ``SNDCTL_DSP_SETFMT`` ioctl, and :meth:`sync` to ``SNDCTL_DSP_SYNC`` (this can
168 be useful when consulting the OSS documentation).  If the underlying
169 :func:`ioctl` fails, they all raise :exc:`IOError`.
170
171
172 .. method:: oss_audio_device.nonblock()
173
174    Put the device into non-blocking mode.  Once in non-blocking mode, there is no
175    way to return it to blocking mode.
176
177
178 .. method:: oss_audio_device.getfmts()
179
180    Return a bitmask of the audio output formats supported by the soundcard.  Some
181    of the formats supported by OSS are:
182
183    +-------------------------+---------------------------------------------+
184    | Format                  | Description                                 |
185    +=========================+=============================================+
186    | :const:`AFMT_MU_LAW`    | a logarithmic encoding (used by Sun ``.au`` |
187    |                         | files and :file:`/dev/audio`)               |
188    +-------------------------+---------------------------------------------+
189    | :const:`AFMT_A_LAW`     | a logarithmic encoding                      |
190    +-------------------------+---------------------------------------------+
191    | :const:`AFMT_IMA_ADPCM` | a 4:1 compressed format defined by the      |
192    |                         | Interactive Multimedia Association          |
193    +-------------------------+---------------------------------------------+
194    | :const:`AFMT_U8`        | Unsigned, 8-bit audio                       |
195    +-------------------------+---------------------------------------------+
196    | :const:`AFMT_S16_LE`    | Signed, 16-bit audio, little-endian byte    |
197    |                         | order (as used by Intel processors)         |
198    +-------------------------+---------------------------------------------+
199    | :const:`AFMT_S16_BE`    | Signed, 16-bit audio, big-endian byte order |
200    |                         | (as used by 68k, PowerPC, Sparc)            |
201    +-------------------------+---------------------------------------------+
202    | :const:`AFMT_S8`        | Signed, 8 bit audio                         |
203    +-------------------------+---------------------------------------------+
204    | :const:`AFMT_U16_LE`    | Unsigned, 16-bit little-endian audio        |
205    +-------------------------+---------------------------------------------+
206    | :const:`AFMT_U16_BE`    | Unsigned, 16-bit big-endian audio           |
207    +-------------------------+---------------------------------------------+
208
209    Consult the OSS documentation for a full list of audio formats, and note that
210    most devices support only a subset of these formats.  Some older devices only
211    support :const:`AFMT_U8`; the most common format used today is
212    :const:`AFMT_S16_LE`.
213
214
215 .. method:: oss_audio_device.setfmt(format)
216
217    Try to set the current audio format to *format*---see :meth:`getfmts` for a
218    list.  Returns the audio format that the device was set to, which may not be the
219    requested format.  May also be used to return the current audio format---do this
220    by passing an "audio format" of :const:`AFMT_QUERY`.
221
222
223 .. method:: oss_audio_device.channels(nchannels)
224
225    Set the number of output channels to *nchannels*.  A value of 1 indicates
226    monophonic sound, 2 stereophonic.  Some devices may have more than 2 channels,
227    and some high-end devices may not support mono. Returns the number of channels
228    the device was set to.
229
230
231 .. method:: oss_audio_device.speed(samplerate)
232
233    Try to set the audio sampling rate to *samplerate* samples per second.  Returns
234    the rate actually set.  Most sound devices don't support arbitrary sampling
235    rates.  Common rates are:
236
237    +-------+-------------------------------------------+
238    | Rate  | Description                               |
239    +=======+===========================================+
240    | 8000  | default rate for :file:`/dev/audio`       |
241    +-------+-------------------------------------------+
242    | 11025 | speech recording                          |
243    +-------+-------------------------------------------+
244    | 22050 |                                           |
245    +-------+-------------------------------------------+
246    | 44100 | CD quality audio (at 16 bits/sample and 2 |
247    |       | channels)                                 |
248    +-------+-------------------------------------------+
249    | 96000 | DVD quality audio (at 24 bits/sample)     |
250    +-------+-------------------------------------------+
251
252
253 .. method:: oss_audio_device.sync()
254
255    Wait until the sound device has played every byte in its buffer.  (This happens
256    implicitly when the device is closed.)  The OSS documentation recommends closing
257    and re-opening the device rather than using :meth:`sync`.
258
259
260 .. method:: oss_audio_device.reset()
261
262    Immediately stop playing or recording and return the device to a state where it
263    can accept commands.  The OSS documentation recommends closing and re-opening
264    the device after calling :meth:`reset`.
265
266
267 .. method:: oss_audio_device.post()
268
269    Tell the driver that there is likely to be a pause in the output, making it
270    possible for the device to handle the pause more intelligently.  You might use
271    this after playing a spot sound effect, before waiting for user input, or before
272    doing disk I/O.
273
274 The following convenience methods combine several ioctls, or one ioctl and some
275 simple calculations.
276
277
278 .. method:: oss_audio_device.setparameters(format, nchannels, samplerate [, strict=False])
279
280    Set the key audio sampling parameters---sample format, number of channels, and
281    sampling rate---in one method call.  *format*,  *nchannels*, and *samplerate*
282    should be as specified in the :meth:`setfmt`, :meth:`channels`, and
283    :meth:`speed`  methods.  If *strict* is true, :meth:`setparameters` checks to
284    see if each parameter was actually set to the requested value, and raises
285    :exc:`OSSAudioError` if not.  Returns a tuple (*format*, *nchannels*,
286    *samplerate*) indicating the parameter values that were actually set by the
287    device driver (i.e., the same as the return values of :meth:`setfmt`,
288    :meth:`channels`, and :meth:`speed`).
289
290    For example,  ::
291
292       (fmt, channels, rate) = dsp.setparameters(fmt, channels, rate)
293
294    is equivalent to  ::
295
296       fmt = dsp.setfmt(fmt)
297       channels = dsp.channels(channels)
298       rate = dsp.rate(channels)
299
300
301 .. method:: oss_audio_device.bufsize()
302
303    Returns the size of the hardware buffer, in samples.
304
305
306 .. method:: oss_audio_device.obufcount()
307
308    Returns the number of samples that are in the hardware buffer yet to be played.
309
310
311 .. method:: oss_audio_device.obuffree()
312
313    Returns the number of samples that could be queued into the hardware buffer to
314    be played without blocking.
315
316 Audio device objects also support several read-only attributes:
317
318
319 .. attribute:: oss_audio_device.closed
320
321    Boolean indicating whether the device has been closed.
322
323
324 .. attribute:: oss_audio_device.name
325
326    String containing the name of the device file.
327
328
329 .. attribute:: oss_audio_device.mode
330
331    The I/O mode for the file, either ``"r"``, ``"rw"``, or ``"w"``.
332
333
334 .. _mixer-device-objects:
335
336 Mixer Device Objects
337 --------------------
338
339 The mixer object provides two file-like methods:
340
341
342 .. method:: oss_mixer_device.close()
343
344    This method closes the open mixer device file.  Any further attempts to use the
345    mixer after this file is closed will raise an :exc:`IOError`.
346
347
348 .. method:: oss_mixer_device.fileno()
349
350    Returns the file handle number of the open mixer device file.
351
352 The remaining methods are specific to audio mixing:
353
354
355 .. method:: oss_mixer_device.controls()
356
357    This method returns a bitmask specifying the available mixer controls ("Control"
358    being a specific mixable "channel", such as :const:`SOUND_MIXER_PCM` or
359    :const:`SOUND_MIXER_SYNTH`).  This bitmask indicates a subset of all available
360    mixer controls---the :const:`SOUND_MIXER_\*` constants defined at module level.
361    To determine if, for example, the current mixer object supports a PCM mixer, use
362    the following Python code::
363
364       mixer=ossaudiodev.openmixer()
365       if mixer.controls() & (1 << ossaudiodev.SOUND_MIXER_PCM):
366           # PCM is supported
367           ... code ...
368
369    For most purposes, the :const:`SOUND_MIXER_VOLUME` (master volume) and
370    :const:`SOUND_MIXER_PCM` controls should suffice---but code that uses the mixer
371    should be flexible when it comes to choosing mixer controls.  On the Gravis
372    Ultrasound, for example, :const:`SOUND_MIXER_VOLUME` does not exist.
373
374
375 .. method:: oss_mixer_device.stereocontrols()
376
377    Returns a bitmask indicating stereo mixer controls.  If a bit is set, the
378    corresponding control is stereo; if it is unset, the control is either
379    monophonic or not supported by the mixer (use in combination with
380    :meth:`controls` to determine which).
381
382    See the code example for the :meth:`controls` function for an example of getting
383    data from a bitmask.
384
385
386 .. method:: oss_mixer_device.reccontrols()
387
388    Returns a bitmask specifying the mixer controls that may be used to record.  See
389    the code example for :meth:`controls` for an example of reading from a bitmask.
390
391
392 .. method:: oss_mixer_device.get(control)
393
394    Returns the volume of a given mixer control.  The returned volume is a 2-tuple
395    ``(left_volume,right_volume)``.  Volumes are specified as numbers from 0
396    (silent) to 100 (full volume).  If the control is monophonic, a 2-tuple is still
397    returned, but both volumes are the same.
398
399    Raises :exc:`OSSAudioError` if an invalid control was is specified, or
400    :exc:`IOError` if an unsupported control is specified.
401
402
403 .. method:: oss_mixer_device.set(control, (left, right))
404
405    Sets the volume for a given mixer control to ``(left,right)``. ``left`` and
406    ``right`` must be ints and between 0 (silent) and 100 (full volume).  On
407    success, the new volume is returned as a 2-tuple. Note that this may not be
408    exactly the same as the volume specified, because of the limited resolution of
409    some soundcard's mixers.
410
411    Raises :exc:`OSSAudioError` if an invalid mixer control was specified, or if the
412    specified volumes were out-of-range.
413
414
415 .. method:: oss_mixer_device.get_recsrc()
416
417    This method returns a bitmask indicating which control(s) are currently being
418    used as a recording source.
419
420
421 .. method:: oss_mixer_device.set_recsrc(bitmask)
422
423    Call this function to specify a recording source.  Returns a bitmask indicating
424    the new recording source (or sources) if successful; raises :exc:`IOError` if an
425    invalid source was specified.  To set the current recording source to the
426    microphone input::
427
428       mixer.setrecsrc (1 << ossaudiodev.SOUND_MIXER_MIC)
429