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