summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMatthias Geier <Matthias.Geier@gmail.com>2019-09-17 20:11:40 +0200
committerMatthias Geier <Matthias.Geier@gmail.com>2019-09-18 13:10:25 +0200
commite8253a615d6f70f7a1f6bc662e703a857fd2e8c4 (patch)
tree788e9cc9efbf15cd2656afb7573cd0c68143d249
parentf5d8fd58924e12fac69c83cd9e3c6250ed8ad868 (diff)
DOC: Documentation overhaul
-rw-r--r--CONTRIBUTING.rst3
-rw-r--r--NEWS.rst28
-rw-r--r--_sounddevice_data/README5
-rw-r--r--doc/README2
-rw-r--r--doc/usage.rst111
-rw-r--r--doc/version-history.rst2
-rw-r--r--setup.py1
-rw-r--r--sounddevice.py91
8 files changed, 185 insertions, 58 deletions
diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst
index 2d14c16..218dc72 100644
--- a/CONTRIBUTING.rst
+++ b/CONTRIBUTING.rst
@@ -6,13 +6,14 @@ please create an issue or a pull request at
https://github.com/spatialaudio/python-sounddevice/.
Contributions are always welcome!
-Instead of pip-installing the latest release from PyPI, you should get the
+Instead of pip-installing the latest release from PyPI_, you should get the
newest development version from Github_::
git clone --recursive https://github.com/spatialaudio/python-sounddevice.git
cd python-sounddevice
python3 setup.py develop --user
+.. _PyPI: https://pypi.org/project/sounddevice/
.. _Github: https://github.com/spatialaudio/python-sounddevice/
This way, your installation always stays up-to-date, even if you pull new
diff --git a/NEWS.rst b/NEWS.rst
index bc6a0be..af9d6e5 100644
--- a/NEWS.rst
+++ b/NEWS.rst
@@ -11,16 +11,16 @@
* Change the way how the PortAudio library is located
0.3.9 (2017-10-25):
- * Add `sounddevice.Stream.closed`
+ * Add `Stream.closed`
* Switch CFFI usage to "out-of-line ABI" mode
0.3.8 (2017-07-11):
* Add more ``ignore_errors`` arguments
- * Add `sounddevice.PortAudioError.args`
- * Add `sounddevice.CoreAudioSettings`
+ * Add `PortAudioError.args`
+ * Add `CoreAudioSettings`
0.3.7 (2017-02-16):
- * Add `sounddevice.get_stream()`
+ * Add `get_stream()`
* Support for CData function pointers as callbacks
0.3.6 (2016-12-19):
@@ -28,27 +28,26 @@
0.3.5 (2016-09-12):
* Add ``extra_settings`` option for host-API-specific stream settings
- * Add `sounddevice.AsioSettings` and `sounddevice.WasapiSettings`
+ * Add `AsioSettings` and `WasapiSettings`
0.3.4 (2016-08-05):
* Example application ``rec_unlimited.py``
0.3.3 (2016-04-11):
- * Add ``loop`` argument to `sounddevice.play()`
+ * Add ``loop`` argument to `play()`
0.3.2 (2016-03-16):
* ``mapping=[1]`` works now on all host APIs
* Example application ``plot_input.py`` showing the live microphone signal(s)
- * Device substrings are now allowed in `sounddevice.query_devices()`
+ * Device substrings are now allowed in `query_devices()`
0.3.1 (2016-01-04):
- * Add `sounddevice.check_input_settings()` and
- `sounddevice.check_output_settings()`
+ * Add `check_input_settings()` and `check_output_settings()`
* Send PortAudio output to ``/dev/null`` (on Linux and OSX)
0.3.0 (2015-10-28):
- * Remove `sounddevice.print_devices()`, `sounddevice.query_devices()` can be
- used instead, since it now returns a `sounddevice.DeviceList` object.
+ * Remove `print_devices()`, `query_devices()` can be used instead,
+ since it now returns a `DeviceList` object.
0.2.2 (2015-10-21):
* Devices can now be selected by substrings of device name and host API name
@@ -61,10 +60,9 @@
* Support for wheels including a dylib for Mac OS X and DLLs for Windows.
The code for creating the wheels is largely taken from PySoundFile_.
* Remove logging (this seemed too intrusive)
- * Return callback status from `sounddevice.wait()` and add the new function
- `sounddevice.get_status()`
- * `sounddevice.playrec()`: Rename the arguments *input_channels* and
- *input_dtype* to *channels* and *dtype*, respectively
+ * Return callback status from `wait()` and add the new function `get_status()`
+ * `playrec()`: Rename the arguments *input_channels* and *input_dtype*
+ to *channels* and *dtype*, respectively
.. _PySoundFile: https://github.com/bastibe/SoundFile/
diff --git a/_sounddevice_data/README b/_sounddevice_data/README
new file mode 100644
index 0000000..e0e1066
--- /dev/null
+++ b/_sounddevice_data/README
@@ -0,0 +1,5 @@
+This directory contains a Git submodule with the .dylib and .dll files
+of the PortAudio library for macOS and Windows, respectively.
+If needed, you can download the submodule with:
+
+ git submodule update --init
diff --git a/doc/README b/doc/README
new file mode 100644
index 0000000..ceb9350
--- /dev/null
+++ b/doc/README
@@ -0,0 +1,2 @@
+This directory contains the source files for the user documentation.
+The rendered result can be found at https://python-sounddevice.readthedocs.io/
diff --git a/doc/usage.rst b/doc/usage.rst
index 37e49a6..53b33d0 100644
--- a/doc/usage.rst
+++ b/doc/usage.rst
@@ -1,3 +1,5 @@
+.. currentmodule:: sounddevice
+
Usage
=====
@@ -12,21 +14,28 @@ Playback
Assuming you have a NumPy array named ``myarray`` holding audio data with a
sampling frequency of ``fs`` (in the most cases this will be 44100 or 48000
-frames per second), you can play it back with `sounddevice.play()`:
+frames per second), you can play it back with `play()`:
.. code:: python
sd.play(myarray, fs)
This function returns immediately but continues playing the audio signal in the
-background. You can stop playback with `sounddevice.stop()`:
+background. You can stop playback with `stop()`:
.. code:: python
sd.stop()
+If you want to block the Python interpreter until playback is finished,
+you can use `wait()`:
+
+.. code:: python
+
+ sd.wait()
+
If you know that you will use the same sampling frequency for a while, you can
-set it as default using `sounddevice.default.samplerate`:
+set it as default using `default.samplerate`:
.. code:: python
@@ -38,18 +47,23 @@ After that, you can drop the *samplerate* argument:
sd.play(myarray)
+.. note::
+
+ If you don't specify the correct sampling frequency,
+ the sound might be played back too slow or too fast!
+
Recording
---------
-To record audio data from your sound device into a NumPy array, use
-`sounddevice.rec()`:
+To record audio data from your sound device into a NumPy array,
+you can use `rec()`:
.. code:: python
duration = 10.5 # seconds
myrecording = sd.rec(int(duration * fs), samplerate=fs, channels=2)
-Again, for repeated use you can set defaults using `sounddevice.default`:
+Again, for repeated use you can set defaults using `default`:
.. code:: python
@@ -62,41 +76,35 @@ After that, you can drop the additional arguments:
myrecording = sd.rec(int(duration * fs))
-This function also returns immediately but continues recording in the
-background. In the meantime, you can run other commands. If you want to check
-if the recording is finished, you should use `sounddevice.wait()`:
+This function also returns immediately but continues recording in the background.
+In the meantime, you can run other commands.
+If you want to check if the recording is finished, you should use `wait()`:
.. code:: python
sd.wait()
-If the recording was already finished, this returns immediately; if not, it
-waits and returns as soon as the recording is finished.
+If the recording was already finished, this returns immediately;
+if not, it waits and returns as soon as the recording is finished.
-Alternatively, you could have used the *blocking* argument in the first place:
+By default, the recorded array has the data type ``'float32'``
+(see `default.dtype`), but this can be changed with the *dtype* argument:
.. code:: python
- myrecording = sd.rec(duration * fs, blocking=True)
-
-By default, the recorded array has the data type ``'float32'`` (see
-`sounddevice.default.dtype`), but this can be changed with the *dtype* argument:
-
-.. code:: python
-
- myrecording = sd.rec(duration * fs, dtype='float64')
+ myrecording = sd.rec(int(duration * fs), dtype='float64')
Simultaneous Playback and Recording
-----------------------------------
-To play back an array and record at the same time, use `sounddevice.playrec()`:
+To play back an array and record at the same time, you can use `playrec()`:
.. code:: python
myrecording = sd.playrec(myarray, fs, channels=2)
-The number of output channels is obtained from ``myarray``, but the number of
-input channels still has to be specified.
+The number of output channels is obtained from ``myarray``,
+but the number of input channels still has to be specified.
Again, default values can be used:
@@ -107,26 +115,27 @@ Again, default values can be used:
myrecording = sd.playrec(myarray)
In this case the number of output channels is still taken from ``myarray``
-(which may or may not have 2 channels), but the number of input channels is
-taken from `sounddevice.default.channels`.
+(which may or may not have 2 channels),
+but the number of input channels is taken from `default.channels`.
Device Selection
----------------
In many cases, the default input/output device(s) will be the one(s) you want,
but it is of course possible to choose a different device.
-Use `sounddevice.query_devices()` to get a list of supported devices.
+Use `query_devices()` to get a list of supported devices.
The same list can be obtained from a terminal by typing the command ::
python3 -m sounddevice
You can use the corresponding device ID to select a desired device by assigning
-to `sounddevice.default.device` or by passing it as *device* argument to
-`sounddevice.play()`, `sounddevice.Stream()` etc.
+to `default.device` or by passing it as *device* argument to
+`play()`, `Stream()` etc.
Instead of the numerical device ID, you can also use a space-separated list of
-case-insensitive substrings of the device name (and the host API name, if
-needed). See `sounddevice.default.device` for details.
+case-insensitive substrings of the device name
+(and the host API name, if needed).
+See `default.device` for details.
.. code:: python
@@ -138,7 +147,25 @@ needed). See `sounddevice.default.device` for details.
Callback Streams
----------------
-Callback "wire" with `sounddevice.Stream`:
+The aforementioned convenience functions `play()`, `rec()` and `playrec()`
+(as well as the related functions `wait()`, `stop()`, `get_status()` and
+`get_stream()`) are designed for small scripts and interactive use
+(e.g. in a Jupyter_ notebook).
+They are supposed to be simple and convenient,
+but their use cases are quite limited.
+
+If you need more control (e.g. continuous recording, realtime processing, ...),
+you should use the lower-level "stream" classes
+(e.g. `Stream`, `InputStream`, `RawInputStream`),
+either with the "non-blocking" callback interface or with the "blocking"
+`Stream.read()` and `Stream.write()` methods, see `Blocking Read/Write Streams`_.
+
+As an example for the "non-blocking" interface,
+the following code creates a `Stream` with a callback function
+that obtains audio data from the input channels
+and simply forwards everything to the output channels
+(be careful with the output volume, because this might cause acoustic feedback
+if your microphone is close to your loudspeakers):
.. code:: python
@@ -153,7 +180,8 @@ Callback "wire" with `sounddevice.Stream`:
with sd.Stream(channels=2, callback=callback):
sd.sleep(int(duration * 1000))
-Same thing with `sounddevice.RawStream`:
+The same thing can be done with `RawStream`
+(NumPy_ doesn't have to be installed):
.. code:: python
@@ -171,11 +199,20 @@ Same thing with `sounddevice.RawStream`:
.. note:: We are using 24-bit samples here for no particular reason
(just because we can).
+You can of course extend the callback functions
+to do arbitrarily more complicated stuff.
+You can also use streams without inputs (e.g. `OutputStream`)
+or streams without outputs (e.g. `InputStream`).
+
+See :doc:`examples` for more examples.
+
Blocking Read/Write Streams
---------------------------
-Instead of using a callback function, you can also use the blocking methods
-`sounddevice.Stream.read()` and `sounddevice.Stream.write()` (and of course the
-corresponding methods in `sounddevice.InputStream`, `sounddevice.OutputStream`,
-`sounddevice.RawStream`, `sounddevice.RawInputStream` and
-`sounddevice.RawOutputStream`).
+Instead of using a callback function,
+you can also use the "blocking" methods `Stream.read()` and `Stream.write()`
+(and of course the corresponding methods in `InputStream`, `OutputStream`,
+`RawStream`, `RawInputStream` and `RawOutputStream`).
+
+.. _Jupyter: https://jupyter.org/
+.. _NumPy: https://numpy.org/
diff --git a/doc/version-history.rst b/doc/version-history.rst
index 04c6953..f8d8b7c 100644
--- a/doc/version-history.rst
+++ b/doc/version-history.rst
@@ -1,6 +1,8 @@
Version History
===============
+.. currentmodule:: sounddevice
+
.. default-role:: py:obj
.. include:: ../NEWS.rst
diff --git a/setup.py b/setup.py
index 766cc87..e9e5fbb 100644
--- a/setup.py
+++ b/setup.py
@@ -48,6 +48,7 @@ except ImportError:
else:
class bdist_wheel_half_pure(bdist_wheel):
"""Create OS-dependent, but Python-independent wheels."""
+
def get_tag(self):
pythons = 'py2.py3.' + PYTHON_INTERPRETERS
if system == 'Darwin':
diff --git a/sounddevice.py b/sounddevice.py
index f3a5ee3..3c9ce4c 100644
--- a/sounddevice.py
+++ b/sounddevice.py
@@ -18,7 +18,7 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
-"""Play and Record Sound with Python
+"""Play and Record Sound with Python.
API overview:
* Convenience functions to play and record NumPy arrays:
@@ -104,6 +104,27 @@ def play(data, samplerate=None, mapping=None, blocking=False, loop=False,
**kwargs):
"""Play back a NumPy array containing audio data.
+ This is a convenience function for interactive use and for small
+ scripts. It cannot be used for multiple overlapping playbacks.
+
+ This function does the following steps internally:
+
+ * Call `stop()` to terminate any currently running invocation
+ of `play()`, `rec()` and `playrec()`.
+
+ * Create an `OutputStream` and a callback function for taking care
+ of the actual playback.
+
+ * Start the stream.
+
+ * If ``blocking=True`` was given, wait until playback is done.
+ If not, return immediately.
+
+ If you need more control (e.g. block-wise gapless playback, multiple
+ overlapping playbacks, ...), you should explicitly create an
+ `OutputStream` yourself.
+ If NumPy is not available, you can use a `RawOutputStream`.
+
Parameters
----------
data : array_like
@@ -134,6 +155,13 @@ def play(data, samplerate=None, mapping=None, blocking=False, loop=False,
All parameters of `OutputStream` -- except *channels*, *dtype*,
*callback* and *finished_callback* -- can be used.
+ Notes
+ -----
+ If you don't specify the correct sampling rate
+ (either with the *samplerate* argument or by assigning a value to
+ `default.samplerate`), the audio data will be played back,
+ but it might be too slow or too fast!
+
See Also
--------
rec, playrec
@@ -158,6 +186,27 @@ def rec(frames=None, samplerate=None, channels=None, dtype=None,
out=None, mapping=None, blocking=False, **kwargs):
"""Record audio data into a NumPy array.
+ This is a convenience function for interactive use and for small
+ scripts.
+
+ This function does the following steps internally:
+
+ * Call `stop()` to terminate any currently running invocation
+ of `play()`, `rec()` and `playrec()`.
+
+ * Create an `InputStream` and a callback function for taking care
+ of the actual recording.
+
+ * Start the stream.
+
+ * If ``blocking=True`` was given, wait until recording is done.
+ If not, return immediately.
+
+ If you need more control (e.g. block-wise gapless recording,
+ overlapping recordings, ...), you should explicitly create an
+ `InputStream` yourself.
+ If NumPy is not available, you can use a `RawInputStream`.
+
Parameters
----------
frames : int, sometimes optional
@@ -206,6 +255,13 @@ def rec(frames=None, samplerate=None, channels=None, dtype=None,
All parameters of `InputStream` -- except *callback* and
*finished_callback* -- can be used.
+ Notes
+ -----
+ If you don't specify a sampling rate (either with the *samplerate*
+ argument or by assigning a value to `default.samplerate`),
+ the default sampling rate of the sound device will be used
+ (see `query_devices()`).
+
See Also
--------
play, playrec
@@ -230,6 +286,24 @@ def playrec(data, samplerate=None, channels=None, dtype=None,
**kwargs):
"""Simultaneous playback and recording of NumPy arrays.
+ This function does the following steps internally:
+
+ * Call `stop()` to terminate any currently running invocation
+ of `play()`, `rec()` and `playrec()`.
+
+ * Create a `Stream` and a callback function for taking care of the
+ actual playback and recording.
+
+ * Start the stream.
+
+ * If ``blocking=True`` was given, wait until playback/recording is
+ done. If not, return immediately.
+
+ If you need more control (e.g. block-wise gapless playback and
+ recording, realtime processing, ...),
+ you should explicitly create a `Stream` yourself.
+ If NumPy is not available, you can use a `RawStream`.
+
Parameters
----------
data : array_like
@@ -265,6 +339,13 @@ def playrec(data, samplerate=None, channels=None, dtype=None,
All parameters of `Stream` -- except *channels*, *dtype*,
*callback* and *finished_callback* -- can be used.
+ Notes
+ -----
+ If you don't specify the correct sampling rate
+ (either with the *samplerate* argument or by assigning a value to
+ `default.samplerate`), the audio data will be played back,
+ but it might be too slow or too fast!
+
See Also
--------
play, rec
@@ -1823,7 +1904,7 @@ class CallbackFlags(object):
return self._hasflag(_lib.paPrimingOutput)
def _hasflag(self, flag):
- """Helper function to check a given flag."""
+ """Check a given flag."""
return bool(self._flags & flag)
@@ -1864,7 +1945,6 @@ class default(object):
Examples
--------
-
>>> import sounddevice as sd
>>> sd.default.samplerate = 48000
>>> sd.default.dtype
@@ -1891,6 +1971,7 @@ class default(object):
>>> sd.default.reset()
"""
+
_pairs = 'device', 'channels', 'dtype', 'latency', 'extra_settings'
# The class attributes listed in _pairs are only provided here for static
# analysis tools and for the docs. They're overwritten in __init__().
@@ -2324,7 +2405,7 @@ class _CallbackContext(object):
# In this case, we play silence on the second channel, but only if the
# device actually supports a second channel:
if (mapping_is_explicit and np.array_equal(mapping, [0]) and
- query_devices(device, 'output')['max_output_channels'] >= 2):
+ query_devices(device, 'output')['max_output_channels'] >= 2):
channels = 2
silent_channels = np.setdiff1d(np.arange(channels), mapping)
if len(mapping) + len(silent_channels) != channels:
@@ -2643,7 +2724,7 @@ def _initialize():
This temporarily forwards messages from stderr to /dev/null
(where supported).
-
+
"""
old_stderr = None
try: