blob: 3972f14bcb37ef3bf27f8424908a061a8352952f [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2:mod:`ossaudiodev` --- Access to OSS-compatible audio devices
3=============================================================
4
5.. module:: ossaudiodev
6 :platform: Linux, FreeBSD
7 :synopsis: Access to OSS-compatible audio devices.
8
9
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
17 is active to use ossaudiodev, but you're gonna need it for the vast
18 majority of Linux audio apps anyways.
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
42
43.. seealso::
44
45 `Open Sound System Programmer's Guide <http://www.opensound.com/pguide/oss.pdf>`_
46 the official documentation for the OSS C API
47
48 The module defines a large number of constants supplied by the OSS device
49 driver; see ``<sys/soundcard.h>`` on either Linux or FreeBSD for a listing .
50
51:mod:`ossaudiodev` defines the following variables and functions:
52
53
54.. exception:: OSSAudioError
55
56 This exception is raised on certain errors. The argument is a string describing
57 what went wrong.
58
59 (If :mod:`ossaudiodev` receives an error from a system call such as
60 :cfunc:`open`, :cfunc:`write`, or :cfunc:`ioctl`, it raises :exc:`IOError`.
61 Errors detected directly by :mod:`ossaudiodev` result in :exc:`OSSAudioError`.)
62
63 (For backwards compatibility, the exception class is also available as
64 ``ossaudiodev.error``.)
65
66
67.. function:: open([device, ]mode)
68
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
163The following methods each map to exactly one :func:`ioctl` system call. The
164correspondence is obvious: for example, :meth:`setfmt` corresponds to the
165``SNDCTL_DSP_SETFMT`` ioctl, and :meth:`sync` to ``SNDCTL_DSP_SYNC`` (this can
166be useful when consulting the OSS documentation). If the underlying
167:func:`ioctl` fails, they all raise :exc:`IOError`.
168
169
170.. method:: oss_audio_device.nonblock()
171
172 Put the device into non-blocking mode. Once in non-blocking mode, there is no
173 way to return it to blocking mode.
174
175
176.. method:: oss_audio_device.getfmts()
177
178 Return a bitmask of the audio output formats supported by the soundcard. Some
179 of the formats supported by OSS are:
180
181 +-------------------------+---------------------------------------------+
182 | Format | Description |
183 +=========================+=============================================+
184 | :const:`AFMT_MU_LAW` | a logarithmic encoding (used by Sun ``.au`` |
185 | | files and :file:`/dev/audio`) |
186 +-------------------------+---------------------------------------------+
187 | :const:`AFMT_A_LAW` | a logarithmic encoding |
188 +-------------------------+---------------------------------------------+
189 | :const:`AFMT_IMA_ADPCM` | a 4:1 compressed format defined by the |
190 | | Interactive Multimedia Association |
191 +-------------------------+---------------------------------------------+
192 | :const:`AFMT_U8` | Unsigned, 8-bit audio |
193 +-------------------------+---------------------------------------------+
194 | :const:`AFMT_S16_LE` | Signed, 16-bit audio, little-endian byte |
195 | | order (as used by Intel processors) |
196 +-------------------------+---------------------------------------------+
197 | :const:`AFMT_S16_BE` | Signed, 16-bit audio, big-endian byte order |
198 | | (as used by 68k, PowerPC, Sparc) |
199 +-------------------------+---------------------------------------------+
200 | :const:`AFMT_S8` | Signed, 8 bit audio |
201 +-------------------------+---------------------------------------------+
202 | :const:`AFMT_U16_LE` | Unsigned, 16-bit little-endian audio |
203 +-------------------------+---------------------------------------------+
204 | :const:`AFMT_U16_BE` | Unsigned, 16-bit big-endian audio |
205 +-------------------------+---------------------------------------------+
206
207 Consult the OSS documentation for a full list of audio formats, and note that
208 most devices support only a subset of these formats. Some older devices only
209 support :const:`AFMT_U8`; the most common format used today is
210 :const:`AFMT_S16_LE`.
211
212
213.. method:: oss_audio_device.setfmt(format)
214
215 Try to set the current audio format to *format*---see :meth:`getfmts` for a
216 list. Returns the audio format that the device was set to, which may not be the
217 requested format. May also be used to return the current audio format---do this
218 by passing an "audio format" of :const:`AFMT_QUERY`.
219
220
221.. method:: oss_audio_device.channels(nchannels)
222
223 Set the number of output channels to *nchannels*. A value of 1 indicates
224 monophonic sound, 2 stereophonic. Some devices may have more than 2 channels,
225 and some high-end devices may not support mono. Returns the number of channels
226 the device was set to.
227
228
229.. method:: oss_audio_device.speed(samplerate)
230
231 Try to set the audio sampling rate to *samplerate* samples per second. Returns
232 the rate actually set. Most sound devices don't support arbitrary sampling
233 rates. Common rates are:
234
235 +-------+-------------------------------------------+
236 | Rate | Description |
237 +=======+===========================================+
238 | 8000 | default rate for :file:`/dev/audio` |
239 +-------+-------------------------------------------+
240 | 11025 | speech recording |
241 +-------+-------------------------------------------+
242 | 22050 | |
243 +-------+-------------------------------------------+
244 | 44100 | CD quality audio (at 16 bits/sample and 2 |
245 | | channels) |
246 +-------+-------------------------------------------+
247 | 96000 | DVD quality audio (at 24 bits/sample) |
248 +-------+-------------------------------------------+
249
250
251.. method:: oss_audio_device.sync()
252
253 Wait until the sound device has played every byte in its buffer. (This happens
254 implicitly when the device is closed.) The OSS documentation recommends closing
255 and re-opening the device rather than using :meth:`sync`.
256
257
258.. method:: oss_audio_device.reset()
259
260 Immediately stop playing or recording and return the device to a state where it
261 can accept commands. The OSS documentation recommends closing and re-opening
262 the device after calling :meth:`reset`.
263
264
265.. method:: oss_audio_device.post()
266
267 Tell the driver that there is likely to be a pause in the output, making it
268 possible for the device to handle the pause more intelligently. You might use
269 this after playing a spot sound effect, before waiting for user input, or before
270 doing disk I/O.
271
272The following convenience methods combine several ioctls, or one ioctl and some
273simple calculations.
274
275
276.. method:: oss_audio_device.setparameters(format, nchannels, samplerate [, strict=False])
277
278 Set the key audio sampling parameters---sample format, number of channels, and
279 sampling rate---in one method call. *format*, *nchannels*, and *samplerate*
280 should be as specified in the :meth:`setfmt`, :meth:`channels`, and
281 :meth:`speed` methods. If *strict* is true, :meth:`setparameters` checks to
282 see if each parameter was actually set to the requested value, and raises
283 :exc:`OSSAudioError` if not. Returns a tuple (*format*, *nchannels*,
284 *samplerate*) indicating the parameter values that were actually set by the
285 device driver (i.e., the same as the return values of :meth:`setfmt`,
286 :meth:`channels`, and :meth:`speed`).
287
288 For example, ::
289
290 (fmt, channels, rate) = dsp.setparameters(fmt, channels, rate)
291
292 is equivalent to ::
293
294 fmt = dsp.setfmt(fmt)
295 channels = dsp.channels(channels)
296 rate = dsp.rate(channels)
297
298
299.. method:: oss_audio_device.bufsize()
300
301 Returns the size of the hardware buffer, in samples.
302
303
304.. method:: oss_audio_device.obufcount()
305
306 Returns the number of samples that are in the hardware buffer yet to be played.
307
308
309.. method:: oss_audio_device.obuffree()
310
311 Returns the number of samples that could be queued into the hardware buffer to
312 be played without blocking.
313
314Audio device objects also support several read-only attributes:
315
316
317.. attribute:: oss_audio_device.closed
318
319 Boolean indicating whether the device has been closed.
320
321
322.. attribute:: oss_audio_device.name
323
324 String containing the name of the device file.
325
326
327.. attribute:: oss_audio_device.mode
328
329 The I/O mode for the file, either ``"r"``, ``"rw"``, or ``"w"``.
330
331
332.. _mixer-device-objects:
333
334Mixer Device Objects
335--------------------
336
337The mixer object provides two file-like methods:
338
339
340.. method:: oss_mixer_device.close()
341
342 This method closes the open mixer device file. Any further attempts to use the
343 mixer after this file is closed will raise an :exc:`IOError`.
344
345
346.. method:: oss_mixer_device.fileno()
347
348 Returns the file handle number of the open mixer device file.
349
350The remaining methods are specific to audio mixing:
351
352
353.. method:: oss_mixer_device.controls()
354
355 This method returns a bitmask specifying the available mixer controls ("Control"
356 being a specific mixable "channel", such as :const:`SOUND_MIXER_PCM` or
357 :const:`SOUND_MIXER_SYNTH`). This bitmask indicates a subset of all available
358 mixer controls---the :const:`SOUND_MIXER_\*` constants defined at module level.
359 To determine if, for example, the current mixer object supports a PCM mixer, use
360 the following Python code::
361
362 mixer=ossaudiodev.openmixer()
363 if mixer.controls() & (1 << ossaudiodev.SOUND_MIXER_PCM):
364 # PCM is supported
365 ... code ...
366
367 For most purposes, the :const:`SOUND_MIXER_VOLUME` (master volume) and
368 :const:`SOUND_MIXER_PCM` controls should suffice---but code that uses the mixer
369 should be flexible when it comes to choosing mixer controls. On the Gravis
370 Ultrasound, for example, :const:`SOUND_MIXER_VOLUME` does not exist.
371
372
373.. method:: oss_mixer_device.stereocontrols()
374
375 Returns a bitmask indicating stereo mixer controls. If a bit is set, the
376 corresponding control is stereo; if it is unset, the control is either
377 monophonic or not supported by the mixer (use in combination with
378 :meth:`controls` to determine which).
379
380 See the code example for the :meth:`controls` function for an example of getting
381 data from a bitmask.
382
383
384.. method:: oss_mixer_device.reccontrols()
385
386 Returns a bitmask specifying the mixer controls that may be used to record. See
387 the code example for :meth:`controls` for an example of reading from a bitmask.
388
389
390.. method:: oss_mixer_device.get(control)
391
392 Returns the volume of a given mixer control. The returned volume is a 2-tuple
393 ``(left_volume,right_volume)``. Volumes are specified as numbers from 0
394 (silent) to 100 (full volume). If the control is monophonic, a 2-tuple is still
395 returned, but both volumes are the same.
396
397 Raises :exc:`OSSAudioError` if an invalid control was is specified, or
398 :exc:`IOError` if an unsupported control is specified.
399
400
401.. method:: oss_mixer_device.set(control, (left, right))
402
403 Sets the volume for a given mixer control to ``(left,right)``. ``left`` and
404 ``right`` must be ints and between 0 (silent) and 100 (full volume). On
405 success, the new volume is returned as a 2-tuple. Note that this may not be
406 exactly the same as the volume specified, because of the limited resolution of
407 some soundcard's mixers.
408
409 Raises :exc:`OSSAudioError` if an invalid mixer control was specified, or if the
410 specified volumes were out-of-range.
411
412
413.. method:: oss_mixer_device.get_recsrc()
414
415 This method returns a bitmask indicating which control(s) are currently being
416 used as a recording source.
417
418
419.. method:: oss_mixer_device.set_recsrc(bitmask)
420
421 Call this function to specify a recording source. Returns a bitmask indicating
422 the new recording source (or sources) if successful; raises :exc:`IOError` if an
423 invalid source was specified. To set the current recording source to the
424 microphone input::
425
426 mixer.setrecsrc (1 << ossaudiodev.SOUND_MIXER_MIC)
427