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