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