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