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