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