2 :mod:`ossaudiodev` --- Access to OSS-compatible audio devices
3 =============================================================
5 .. module:: ossaudiodev
6 :platform: Linux, FreeBSD
7 :synopsis: Access to OSS-compatible audio devices.
12 This module allows you to access the OSS (Open Sound System) audio interface.
13 OSS is available for a wide range of open-source and commercial Unices, and is
14 the standard audio interface for Linux and recent versions of FreeBSD.
16 .. Things will get more complicated for future Linux versions, since
17 ALSA is in the standard kernel as of 2.5.x. Presumably if you
18 use ALSA, you'll have to make sure its OSS compatibility layer
19 is active to use ossaudiodev, but you're gonna need it for the vast
20 majority of Linux audio apps anyways.
22 Sounds like things are also complicated for other BSDs. In response
23 to my python-dev query, Thomas Wouters said:
25 > Likewise, googling shows OpenBSD also uses OSS/Free -- the commercial
26 > OSS installation manual tells you to remove references to OSS/Free from the
29 but Aleksander Piotrowsk actually has an OpenBSD box, and he quotes
30 from its <soundcard.h>:
32 > * This is an OSS (Linux) audio emulator.
33 > * Use the Native NetBSD API for developing new code, and this
34 > * only for compiling Linux programs.
36 There's also an ossaudio manpage on OpenBSD that explains things
37 further. Presumably NetBSD and OpenBSD have a different standard
38 audio interface. That's the great thing about standards, there are so
39 many to choose from ... ;-)
41 This probably all warrants a footnote or two, but I don't understand
42 things well enough right now to write it! --GPW
47 `Open Sound System Programmer's Guide <http://www.opensound.com/pguide/oss.pdf>`_
48 the official documentation for the OSS C API
50 The module defines a large number of constants supplied by the OSS device
51 driver; see ``<sys/soundcard.h>`` on either Linux or FreeBSD for a listing .
53 :mod:`ossaudiodev` defines the following variables and functions:
56 .. exception:: OSSAudioError
58 This exception is raised on certain errors. The argument is a string describing
61 (If :mod:`ossaudiodev` receives an error from a system call such as
62 :cfunc:`open`, :cfunc:`write`, or :cfunc:`ioctl`, it raises :exc:`IOError`.
63 Errors detected directly by :mod:`ossaudiodev` result in :exc:`OSSAudioError`.)
65 (For backwards compatibility, the exception class is also available as
66 ``ossaudiodev.error``.)
69 .. function:: open([device, ]mode)
71 Open an audio device and return an OSS audio device object. This object
72 supports many file-like methods, such as :meth:`read`, :meth:`write`, and
73 :meth:`fileno` (although there are subtle differences between conventional Unix
74 read/write semantics and those of OSS audio devices). It also supports a number
75 of audio-specific methods; see below for the complete list of methods.
77 *device* is the audio device filename to use. If it is not specified, this
78 module first looks in the environment variable :envvar:`AUDIODEV` for a device
79 to use. If not found, it falls back to :file:`/dev/dsp`.
81 *mode* is one of ``'r'`` for read-only (record) access, ``'w'`` for
82 write-only (playback) access and ``'rw'`` for both. Since many sound cards
83 only allow one process to have the recorder or player open at a time, it is a
84 good idea to open the device only for the activity needed. Further, some
85 sound cards are half-duplex: they can be opened for reading or writing, but
88 Note the unusual calling syntax: the *first* argument is optional, and the
89 second is required. This is a historical artifact for compatibility with the
90 older :mod:`linuxaudiodev` module which :mod:`ossaudiodev` supersedes.
92 .. XXX it might also be motivated
93 by my unfounded-but-still-possibly-true belief that the default
94 audio device varies unpredictably across operating systems. -GW
97 .. function:: openmixer([device])
99 Open a mixer device and return an OSS mixer device object. *device* is the
100 mixer device filename to use. If it is not specified, this module first looks
101 in the environment variable :envvar:`MIXERDEV` for a device to use. If not
102 found, it falls back to :file:`/dev/mixer`.
105 .. _ossaudio-device-objects:
110 Before you can write to or read from an audio device, you must call three
111 methods in the correct order:
113 #. :meth:`setfmt` to set the output format
115 #. :meth:`channels` to set the number of channels
117 #. :meth:`speed` to set the sample rate
119 Alternately, you can use the :meth:`setparameters` method to set all three audio
120 parameters at once. This is more convenient, but may not be as flexible in all
123 The audio device objects returned by :func:`open` define the following methods
124 and (read-only) attributes:
127 .. method:: oss_audio_device.close()
129 Explicitly close the audio device. When you are done writing to or reading from
130 an audio device, you should explicitly close it. A closed device cannot be used
134 .. method:: oss_audio_device.fileno()
136 Return the file descriptor associated with the device.
139 .. method:: oss_audio_device.read(size)
141 Read *size* bytes from the audio input and return them as a Python string.
142 Unlike most Unix device drivers, OSS audio devices in blocking mode (the
143 default) will block :func:`read` until the entire requested amount of data is
147 .. method:: oss_audio_device.write(data)
149 Write the Python string *data* to the audio device and return the number of
150 bytes written. If the audio device is in blocking mode (the default), the
151 entire string is always written (again, this is different from usual Unix device
152 semantics). If the device is in non-blocking mode, some data may not be written
153 ---see :meth:`writeall`.
156 .. method:: oss_audio_device.writeall(data)
158 Write the entire Python string *data* to the audio device: waits until the audio
159 device is able to accept data, writes as much data as it will accept, and
160 repeats until *data* has been completely written. If the device is in blocking
161 mode (the default), this has the same effect as :meth:`write`; :meth:`writeall`
162 is only useful in non-blocking mode. Has no return value, since the amount of
163 data written is always equal to the amount of data supplied.
165 The following methods each map to exactly one :func:`ioctl` system call. The
166 correspondence is obvious: for example, :meth:`setfmt` corresponds to the
167 ``SNDCTL_DSP_SETFMT`` ioctl, and :meth:`sync` to ``SNDCTL_DSP_SYNC`` (this can
168 be useful when consulting the OSS documentation). If the underlying
169 :func:`ioctl` fails, they all raise :exc:`IOError`.
172 .. method:: oss_audio_device.nonblock()
174 Put the device into non-blocking mode. Once in non-blocking mode, there is no
175 way to return it to blocking mode.
178 .. method:: oss_audio_device.getfmts()
180 Return a bitmask of the audio output formats supported by the soundcard. Some
181 of the formats supported by OSS are:
183 +-------------------------+---------------------------------------------+
184 | Format | Description |
185 +=========================+=============================================+
186 | :const:`AFMT_MU_LAW` | a logarithmic encoding (used by Sun ``.au`` |
187 | | files and :file:`/dev/audio`) |
188 +-------------------------+---------------------------------------------+
189 | :const:`AFMT_A_LAW` | a logarithmic encoding |
190 +-------------------------+---------------------------------------------+
191 | :const:`AFMT_IMA_ADPCM` | a 4:1 compressed format defined by the |
192 | | Interactive Multimedia Association |
193 +-------------------------+---------------------------------------------+
194 | :const:`AFMT_U8` | Unsigned, 8-bit audio |
195 +-------------------------+---------------------------------------------+
196 | :const:`AFMT_S16_LE` | Signed, 16-bit audio, little-endian byte |
197 | | order (as used by Intel processors) |
198 +-------------------------+---------------------------------------------+
199 | :const:`AFMT_S16_BE` | Signed, 16-bit audio, big-endian byte order |
200 | | (as used by 68k, PowerPC, Sparc) |
201 +-------------------------+---------------------------------------------+
202 | :const:`AFMT_S8` | Signed, 8 bit audio |
203 +-------------------------+---------------------------------------------+
204 | :const:`AFMT_U16_LE` | Unsigned, 16-bit little-endian audio |
205 +-------------------------+---------------------------------------------+
206 | :const:`AFMT_U16_BE` | Unsigned, 16-bit big-endian audio |
207 +-------------------------+---------------------------------------------+
209 Consult the OSS documentation for a full list of audio formats, and note that
210 most devices support only a subset of these formats. Some older devices only
211 support :const:`AFMT_U8`; the most common format used today is
212 :const:`AFMT_S16_LE`.
215 .. method:: oss_audio_device.setfmt(format)
217 Try to set the current audio format to *format*---see :meth:`getfmts` for a
218 list. Returns the audio format that the device was set to, which may not be the
219 requested format. May also be used to return the current audio format---do this
220 by passing an "audio format" of :const:`AFMT_QUERY`.
223 .. method:: oss_audio_device.channels(nchannels)
225 Set the number of output channels to *nchannels*. A value of 1 indicates
226 monophonic sound, 2 stereophonic. Some devices may have more than 2 channels,
227 and some high-end devices may not support mono. Returns the number of channels
228 the device was set to.
231 .. method:: oss_audio_device.speed(samplerate)
233 Try to set the audio sampling rate to *samplerate* samples per second. Returns
234 the rate actually set. Most sound devices don't support arbitrary sampling
235 rates. Common rates are:
237 +-------+-------------------------------------------+
238 | Rate | Description |
239 +=======+===========================================+
240 | 8000 | default rate for :file:`/dev/audio` |
241 +-------+-------------------------------------------+
242 | 11025 | speech recording |
243 +-------+-------------------------------------------+
245 +-------+-------------------------------------------+
246 | 44100 | CD quality audio (at 16 bits/sample and 2 |
248 +-------+-------------------------------------------+
249 | 96000 | DVD quality audio (at 24 bits/sample) |
250 +-------+-------------------------------------------+
253 .. method:: oss_audio_device.sync()
255 Wait until the sound device has played every byte in its buffer. (This happens
256 implicitly when the device is closed.) The OSS documentation recommends closing
257 and re-opening the device rather than using :meth:`sync`.
260 .. method:: oss_audio_device.reset()
262 Immediately stop playing or recording and return the device to a state where it
263 can accept commands. The OSS documentation recommends closing and re-opening
264 the device after calling :meth:`reset`.
267 .. method:: oss_audio_device.post()
269 Tell the driver that there is likely to be a pause in the output, making it
270 possible for the device to handle the pause more intelligently. You might use
271 this after playing a spot sound effect, before waiting for user input, or before
274 The following convenience methods combine several ioctls, or one ioctl and some
278 .. method:: oss_audio_device.setparameters(format, nchannels, samplerate [, strict=False])
280 Set the key audio sampling parameters---sample format, number of channels, and
281 sampling rate---in one method call. *format*, *nchannels*, and *samplerate*
282 should be as specified in the :meth:`setfmt`, :meth:`channels`, and
283 :meth:`speed` methods. If *strict* is true, :meth:`setparameters` checks to
284 see if each parameter was actually set to the requested value, and raises
285 :exc:`OSSAudioError` if not. Returns a tuple (*format*, *nchannels*,
286 *samplerate*) indicating the parameter values that were actually set by the
287 device driver (i.e., the same as the return values of :meth:`setfmt`,
288 :meth:`channels`, and :meth:`speed`).
292 (fmt, channels, rate) = dsp.setparameters(fmt, channels, rate)
296 fmt = dsp.setfmt(fmt)
297 channels = dsp.channels(channels)
298 rate = dsp.rate(channels)
301 .. method:: oss_audio_device.bufsize()
303 Returns the size of the hardware buffer, in samples.
306 .. method:: oss_audio_device.obufcount()
308 Returns the number of samples that are in the hardware buffer yet to be played.
311 .. method:: oss_audio_device.obuffree()
313 Returns the number of samples that could be queued into the hardware buffer to
314 be played without blocking.
316 Audio device objects also support several read-only attributes:
319 .. attribute:: oss_audio_device.closed
321 Boolean indicating whether the device has been closed.
324 .. attribute:: oss_audio_device.name
326 String containing the name of the device file.
329 .. attribute:: oss_audio_device.mode
331 The I/O mode for the file, either ``"r"``, ``"rw"``, or ``"w"``.
334 .. _mixer-device-objects:
339 The mixer object provides two file-like methods:
342 .. method:: oss_mixer_device.close()
344 This method closes the open mixer device file. Any further attempts to use the
345 mixer after this file is closed will raise an :exc:`IOError`.
348 .. method:: oss_mixer_device.fileno()
350 Returns the file handle number of the open mixer device file.
352 The remaining methods are specific to audio mixing:
355 .. method:: oss_mixer_device.controls()
357 This method returns a bitmask specifying the available mixer controls ("Control"
358 being a specific mixable "channel", such as :const:`SOUND_MIXER_PCM` or
359 :const:`SOUND_MIXER_SYNTH`). This bitmask indicates a subset of all available
360 mixer controls---the :const:`SOUND_MIXER_\*` constants defined at module level.
361 To determine if, for example, the current mixer object supports a PCM mixer, use
362 the following Python code::
364 mixer=ossaudiodev.openmixer()
365 if mixer.controls() & (1 << ossaudiodev.SOUND_MIXER_PCM):
369 For most purposes, the :const:`SOUND_MIXER_VOLUME` (master volume) and
370 :const:`SOUND_MIXER_PCM` controls should suffice---but code that uses the mixer
371 should be flexible when it comes to choosing mixer controls. On the Gravis
372 Ultrasound, for example, :const:`SOUND_MIXER_VOLUME` does not exist.
375 .. method:: oss_mixer_device.stereocontrols()
377 Returns a bitmask indicating stereo mixer controls. If a bit is set, the
378 corresponding control is stereo; if it is unset, the control is either
379 monophonic or not supported by the mixer (use in combination with
380 :meth:`controls` to determine which).
382 See the code example for the :meth:`controls` function for an example of getting
386 .. method:: oss_mixer_device.reccontrols()
388 Returns a bitmask specifying the mixer controls that may be used to record. See
389 the code example for :meth:`controls` for an example of reading from a bitmask.
392 .. method:: oss_mixer_device.get(control)
394 Returns the volume of a given mixer control. The returned volume is a 2-tuple
395 ``(left_volume,right_volume)``. Volumes are specified as numbers from 0
396 (silent) to 100 (full volume). If the control is monophonic, a 2-tuple is still
397 returned, but both volumes are the same.
399 Raises :exc:`OSSAudioError` if an invalid control was is specified, or
400 :exc:`IOError` if an unsupported control is specified.
403 .. method:: oss_mixer_device.set(control, (left, right))
405 Sets the volume for a given mixer control to ``(left,right)``. ``left`` and
406 ``right`` must be ints and between 0 (silent) and 100 (full volume). On
407 success, the new volume is returned as a 2-tuple. Note that this may not be
408 exactly the same as the volume specified, because of the limited resolution of
409 some soundcard's mixers.
411 Raises :exc:`OSSAudioError` if an invalid mixer control was specified, or if the
412 specified volumes were out-of-range.
415 .. method:: oss_mixer_device.get_recsrc()
417 This method returns a bitmask indicating which control(s) are currently being
418 used as a recording source.
421 .. method:: oss_mixer_device.set_recsrc(bitmask)
423 Call this function to specify a recording source. Returns a bitmask indicating
424 the new recording source (or sources) if successful; raises :exc:`IOError` if an
425 invalid source was specified. To set the current recording source to the
428 mixer.setrecsrc (1 << ossaudiodev.SOUND_MIXER_MIC)