/Doc/library/ossaudiodev.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 429 lines · 280 code · 149 blank · 0 comment · 0 complexity · efe36790c184de619a94c043f00c4cca MD5 · raw file

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