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