pax_global_header00006660000000000000000000000064150751623750014525gustar00rootroot0000000000000052 comment=779a42a24f3c6afdf5599e71af4c5ae7b5b2175f python-sounddevice-0.5.3/000077500000000000000000000000001507516237500153615ustar00rootroot00000000000000python-sounddevice-0.5.3/.github/000077500000000000000000000000001507516237500167215ustar00rootroot00000000000000python-sounddevice-0.5.3/.github/dependabot.yml000066400000000000000000000001661507516237500215540ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: "github-actions" directory: "/" schedule: interval: "weekly" python-sounddevice-0.5.3/.github/workflows/000077500000000000000000000000001507516237500207565ustar00rootroot00000000000000python-sounddevice-0.5.3/.github/workflows/docs.yml000066400000000000000000000022011507516237500224240ustar00rootroot00000000000000name: Build docs and check links on: [push, pull_request] jobs: docs-linkcheck: runs-on: ubuntu-latest steps: - name: Install pandoc run: | sudo apt-get install --no-install-recommends pandoc - name: Set up Python uses: actions/setup-python@v6 with: python-version: "3.10" - name: Double-check Python version run: | python --version - name: Clone Git repository (without depth limitation) uses: actions/checkout@v5 with: fetch-depth: 0 - name: Install dependencies run: | python -m pip install -r doc/requirements.txt - name: Build HTML run: | python -m sphinx -W --keep-going --color -d _build/doctrees/ doc/ _build/html/ -b html - name: Check links run: | python -m sphinx -W --keep-going --color -d _build/doctrees/ doc/ _build/linkcheck/ -b linkcheck - name: Upload linkcheck results uses: actions/upload-artifact@v4 if: ${{ success() || failure() }} with: name: linkcheck path: _build/linkcheck/output.* python-sounddevice-0.5.3/.github/workflows/publish.yml000066400000000000000000000021431507516237500231470ustar00rootroot00000000000000name: Build and publish to PyPI on: [push, pull_request] jobs: build: name: Build distribution runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 with: submodules: true - name: Set up Python uses: actions/setup-python@v6 with: python-version: "3" - name: Install "build" run: | python -m pip install build - name: Build binary wheels and a source tarball run: ./make_dist.sh - name: Store the distribution packages uses: actions/upload-artifact@v4 with: name: dist path: dist publish: name: Upload release to PyPI if: startsWith(github.ref, 'refs/tags/') needs: - build runs-on: ubuntu-latest environment: name: pypi url: https://pypi.org/p/sounddevice permissions: id-token: write steps: - name: Get the artifacts uses: actions/download-artifact@v5 with: name: dist path: dist - name: Publish package distributions to PyPI uses: pypa/gh-action-pypi-publish@release/v1 with: print-hash: true python-sounddevice-0.5.3/.github/workflows/python-versions.yml000066400000000000000000000020561507516237500246730ustar00rootroot00000000000000name: Test with different Python versions on: [push, pull_request] jobs: python: strategy: matrix: python-version: - "3.7" - "3.13" - "pypy-3.7" - "pypy-3.11" runs-on: ubuntu-22.04 steps: - name: Install PortAudio run: | sudo apt-get install --no-install-recommends libportaudio2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v6 with: python-version: ${{ matrix.python-version }} - name: Double-check Python version run: | python --version - name: Clone Git repository uses: actions/checkout@v5 with: path: git-repo - name: Install Python package working-directory: git-repo run: | python -m pip install . - name: Run tests run: | python -m sounddevice python -c "import sounddevice as sd; print(sd._libname)" python -c "import sounddevice as sd; print(sd.get_portaudio_version())" python-sounddevice-0.5.3/.github/workflows/sounddevice-data.yml000066400000000000000000000037361507516237500247310ustar00rootroot00000000000000name: Test PortAudio binaries on: [push, pull_request] jobs: binaries: strategy: matrix: include: - os: macos-latest arch: 'arm64' # Last version with Intel CPU: - os: macos-13 arch: 'x64' - os: windows-latest arch: 'x64' - os: windows-latest arch: 'x86' runs-on: ${{ matrix.os }} steps: - name: Set up Python uses: actions/setup-python@v6 with: python-version: "3.10" architecture: ${{ matrix.arch }} - name: Double-check Python version run: | python --version - name: Clone Git repository (with submodules) uses: actions/checkout@v5 with: path: git-repo submodules: true - name: Install Python package working-directory: git-repo run: | python -m pip install . - name: Import module run: | python -m sounddevice python -c "import sounddevice as sd; print(sd._libname)" python -c "import sounddevice as sd; print(sd.get_portaudio_version())" python -c "import sounddevice as sd; print(sd.query_hostapis())" python -c "import sounddevice as sd; assert 'asio' not in sd._libname" python -c "import sounddevice as sd; assert not any(a['name'] == 'ASIO' for a in sd.query_hostapis())" - name: Import module (using the ASIO DLL) if: startsWith(matrix.os, 'windows') env: SD_ENABLE_ASIO: 1 run: | python -m sounddevice python -c "import sounddevice as sd; print(sd._libname)" python -c "import sounddevice as sd; print(sd.get_portaudio_version())" python -c "import sounddevice as sd; print(sd.query_hostapis())" python -c "import sounddevice as sd; assert 'asio' in sd._libname" python -c "import sounddevice as sd; assert any(a['name'] == 'ASIO' for a in sd.query_hostapis())" python-sounddevice-0.5.3/.gitignore000066400000000000000000000001151507516237500173460ustar00rootroot00000000000000_sounddevice.py *.pyc __pycache__/ build/ dist/ .eggs/ sounddevice.egg-info/ python-sounddevice-0.5.3/.gitmodules000066400000000000000000000002141507516237500175330ustar00rootroot00000000000000[submodule "portaudio-binaries"] path = _sounddevice_data/portaudio-binaries url = https://github.com/spatialaudio/portaudio-binaries.git python-sounddevice-0.5.3/.readthedocs.yml000066400000000000000000000004151507516237500204470ustar00rootroot00000000000000version: 2 build: os: ubuntu-22.04 tools: python: "3" jobs: post_checkout: - git fetch --unshallow || true python: install: - method: pip path: . - requirements: doc/requirements.txt sphinx: configuration: doc/conf.py formats: all python-sounddevice-0.5.3/CONTRIBUTING.rst000066400000000000000000000104571507516237500200310ustar00rootroot00000000000000Contributing ============ If you find bugs, errors, omissions or other things that need improvement, please create an issue or a pull request at https://github.com/spatialaudio/python-sounddevice/. Contributions are always welcome! Reporting Problems ------------------ When creating an issue at https://github.com/spatialaudio/python-sounddevice/issues, please make sure to provide as much useful information as possible. You can use Markdown formatting to show Python code, e.g. :: I have created a script named `my_script.py`: ```python import sounddevice as sd fs = 48000 duration = 1.5 data = sd.rec(int(duration * fs), channels=99) sd.wait() print(data.shape) ``` Please provide minimal code (remove everything that's not necessary to show the problem), but make sure that the code example still has everything that's needed to run it, including all ``import`` statements. You should of course also show what happens when you run your code, e.g. :: Running my script, I got this error: ``` $ python my_script.py Expression 'parameters->channelCount <= maxChans' failed in 'src/hostapi/alsa/pa_linux_alsa.c', line: 1514 Expression 'ValidateParameters( inputParameters, hostApi, StreamDirection_In )' failed in 'src/hostapi/alsa/pa_linux_alsa.c', line: 2818 Traceback (most recent call last): File "my_script.py", line 6, in data = sd.rec(int(duration * fs), channels=99) ... sounddevice.PortAudioError: Error opening InputStream: Invalid number of channels [PaErrorCode -9998] ``` Please remember to provide the full command invocation and the full output. You should only remove lines of output when you know they are irrelevant. You should also mention the operating system and host API you are using (e.g. "Linux/ALSA" or "macOS/Core Audio" or "Windows/WASAPI"). If your problem is related to a certain hardware device, you should provide the list of devices as reported by :: python -m sounddevice If your problem has to do with the version of the PortAudio library you are using, you should provide the output of this script:: import sounddevice as sd print(sd._libname) print(sd.get_portaudio_version()) If you don't want to clutter the issue description with a huge load of gibberish, you can use the ``
`` HTML tag to show some content only on demand::
``` $ python -m sounddevice 0 Built-in Line Input, Core Audio (2 in, 0 out) > 1 Built-in Digital Input, Core Audio (2 in, 0 out) < 2 Built-in Output, Core Audio (0 in, 2 out) 3 Built-in Line Output, Core Audio (0 in, 2 out) 4 Built-in Digital Output, Core Audio (0 in, 2 out) ```
Development Installation ------------------------ Instead of pip-installing the latest release from PyPI_, you should get the newest development version (a.k.a. "master") from Github_:: git clone --recursive https://github.com/spatialaudio/python-sounddevice.git cd python-sounddevice python -m pip install -e . .. _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 changes from the Github repository. Whenever the file ``sounddevice_build.py`` changes (either because you edited it or it was updated by pulling from Github or switching branches), you have to run the last command again. If you used the ``--recursive`` option when cloning, the dynamic libraries for *macOS* and *Windows* should already be available. If not, you can get the submodule with:: git submodule update --init Building the Documentation -------------------------- If you make changes to the documentation, you can locally re-create the HTML pages using Sphinx_. You can install it and a few other necessary packages with:: python -m pip install -r doc/requirements.txt To (re-)build the HTML files, use:: python -m sphinx doc _build The generated files will be available in the directory ``_build/``. If you additionally install sphinx-autobuild_, you can run Sphinx automatically on any changes and conveniently auto-reload the changed pages in your browser:: python -m sphinx_autobuild doc _build --open-browser .. _Sphinx: https://www.sphinx-doc.org/ .. _sphinx-autobuild: https://github.com/executablebooks/sphinx-autobuild python-sounddevice-0.5.3/LICENSE000066400000000000000000000020471507516237500163710ustar00rootroot00000000000000Copyright (c) 2015-2025 Matthias Geier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. python-sounddevice-0.5.3/MANIFEST.in000066400000000000000000000002311507516237500171130ustar00rootroot00000000000000include LICENSE include *.rst include doc/requirements.txt include sounddevice_build.py recursive-include doc *.rst *.py recursive-include examples *.py python-sounddevice-0.5.3/NEWS.rst000066400000000000000000000076411507516237500166770ustar00rootroot000000000000000.5.3 (2025-10-19): * add ``explicit_sample_format`` parameter to `WasapiSettings` 0.5.2 (2025-05-16): * Better error if frames/channels are non-integers 0.5.1 (2024-10-12): * Windows wheel: bundle both non-ASIO and ASIO DLLs, the latter can be chosen by defining the ``SD_ENABLE_ASIO`` environment variable 0.5.0 (2024-08-11): * Remove ASIO support from bundled DLLs (DLLs with ASIO can be manually selected) 0.4.7 (2024-05-27): * support ``paWinWasapiAutoConvert`` with ``auto_convert`` flag in `WasapiSettings` * Avoid exception in `PortAudioError`\ ``.__str__()`` 0.4.6 (2023-02-19): * Redirect stderr with ``os.dup2()`` instead of CFFI calls 0.4.5 (2022-08-21): * Add ``index`` field to device dict * Require Python >= 3.7 * Add PaWasapi_IsLoopback() to cdef (high-level interface not yet available) 0.4.4 (2021-12-31): * Exact device string matches can now include the host API name 0.4.3 (2021-10-20): * Fix dimension check in `Stream.write()` * Provide "universal" (x86_64 and arm64) ``.dylib`` for macOS 0.4.2 (2021-07-18): * Update PortAudio binaries to version 19.7.0 * Wheel names are now shorter 0.4.1 (2020-09-26): * `CallbackFlags` attributes are now writable 0.4.0 (2020-07-18): * Drop support for Python 2.x * Fix memory issues in `play()`, `rec()` and `playrec()` * Example application ``play_stream.py`` 0.3.15 (2020-03-18): * This will be the last release supporting Python 2.x! 0.3.14 (2019-09-25): * Examples ``play_sine.py`` and ``rec_gui.py`` * Redirect ``stderr`` only during initialization 0.3.13 (2019-02-27): * Examples ``asyncio_coroutines.py`` and ``asyncio_generators.py`` 0.3.12 (2018-09-02): * Support for the dylib from Anaconda 0.3.11 (2018-05-07): * Support for the DLL from ``conda-forge`` 0.3.10 (2017-12-22): * Change the way how the PortAudio library is located 0.3.9 (2017-10-25): * Add `Stream.closed` * Switch CFFI usage to "out-of-line ABI" mode 0.3.8 (2017-07-11): * Add more ``ignore_errors`` arguments * Add `PortAudioError.args` * Add `CoreAudioSettings` 0.3.7 (2017-02-16): * Add `get_stream()` * Support for CData function pointers as callbacks 0.3.6 (2016-12-19): * Example application ``play_long_file.py`` 0.3.5 (2016-09-12): * Add ``extra_settings`` option for host-API-specific stream settings * 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 `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 `query_devices()` 0.3.1 (2016-01-04): * 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 ``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 0.2.1 (2015-10-08): * Example applications ``wire.py`` (based on PortAudio's ``patest_wire.c``) and ``spectrogram.py`` (based on code by Mauris Van Hauwe) 0.2.0 (2015-07-03): * Support for wheels including a dylib for Mac OS X and DLLs for Windows. The code for creating the wheels is largely taken from the soundfile_ module. * Remove logging (this seemed too intrusive) * 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 .. _soundfile: https://github.com/bastibe/python-soundfile/ 0.1.0 (2015-06-20): Initial release. Some ideas are taken from PySoundCard_. Thanks to Bastian Bechtold for many fruitful discussions during the development of several features which *python-sounddevice* inherited from there. .. _PySoundCard: https://github.com/bastibe/PySoundCard/ python-sounddevice-0.5.3/README.rst000066400000000000000000000011561507516237500170530ustar00rootroot00000000000000Play and Record Sound with Python ================================= This Python_ module provides bindings for the PortAudio_ library and a few convenience functions to play and record NumPy_ arrays containing audio signals. The ``sounddevice`` module is available for Linux, macOS and Windows. Documentation: https://python-sounddevice.readthedocs.io/ Source code repository and issue tracker: https://github.com/spatialaudio/python-sounddevice/ License: MIT -- see the file ``LICENSE`` for details. .. _Python: https://www.python.org/ .. _PortAudio: http://www.portaudio.com/ .. _NumPy: https://numpy.org/ python-sounddevice-0.5.3/_sounddevice_data/000077500000000000000000000000001507516237500210215ustar00rootroot00000000000000python-sounddevice-0.5.3/_sounddevice_data/README000066400000000000000000000003261507516237500217020ustar00rootroot00000000000000This 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 python-sounddevice-0.5.3/_sounddevice_data/__init__.py000066400000000000000000000000001507516237500231200ustar00rootroot00000000000000python-sounddevice-0.5.3/_sounddevice_data/portaudio-binaries/000077500000000000000000000000001507516237500246215ustar00rootroot00000000000000python-sounddevice-0.5.3/doc/000077500000000000000000000000001507516237500161265ustar00rootroot00000000000000python-sounddevice-0.5.3/doc/README000066400000000000000000000002241507516237500170040ustar00rootroot00000000000000This directory contains the source files for the user documentation. The rendered result can be found at https://python-sounddevice.readthedocs.io/ python-sounddevice-0.5.3/doc/api/000077500000000000000000000000001507516237500166775ustar00rootroot00000000000000python-sounddevice-0.5.3/doc/api/checking-hardware.rst000066400000000000000000000006701507516237500230020ustar00rootroot00000000000000Checking Available Hardware =========================== .. currentmodule:: sounddevice .. topic:: Overview .. autosummary:: :nosignatures: query_devices DeviceList query_hostapis check_input_settings check_output_settings .. autofunction:: query_devices .. autoclass:: DeviceList .. autofunction:: query_hostapis .. autofunction:: check_input_settings .. autofunction:: check_output_settings python-sounddevice-0.5.3/doc/api/convenience-functions.rst000066400000000000000000000007031507516237500237330ustar00rootroot00000000000000Convenience Functions using NumPy Arrays ======================================== .. currentmodule:: sounddevice .. topic:: Overview .. autosummary:: :nosignatures: play rec playrec wait stop get_status get_stream .. autofunction:: play .. autofunction:: rec .. autofunction:: playrec .. autofunction:: wait .. autofunction:: stop .. autofunction:: get_status .. autofunction:: get_stream python-sounddevice-0.5.3/doc/api/expert-mode.rst000066400000000000000000000004551507516237500216660ustar00rootroot00000000000000Expert Mode =========== .. currentmodule:: sounddevice .. topic:: Overview .. autosummary:: :nosignatures: _initialize _terminate _split _StreamBase .. autofunction:: _initialize .. autofunction:: _terminate .. autofunction:: _split .. autoclass:: _StreamBase python-sounddevice-0.5.3/doc/api/index.rst000066400000000000000000000003461507516237500205430ustar00rootroot00000000000000API Documentation ================= .. automodule:: sounddevice ---- .. toctree:: convenience-functions checking-hardware module-defaults platform-specific-settings streams raw-streams misc expert-mode python-sounddevice-0.5.3/doc/api/misc.rst000066400000000000000000000007071507516237500203700ustar00rootroot00000000000000Miscellaneous ============= .. currentmodule:: sounddevice .. topic:: Overview .. autosummary:: :nosignatures: sleep get_portaudio_version CallbackFlags CallbackStop CallbackAbort PortAudioError .. autofunction:: sleep .. autofunction:: get_portaudio_version .. autoclass:: CallbackFlags :members: .. autoexception:: CallbackStop .. autoexception:: CallbackAbort .. autoexception:: PortAudioError python-sounddevice-0.5.3/doc/api/module-defaults.rst000066400000000000000000000001771507516237500225300ustar00rootroot00000000000000Module-wide Default Settings ============================ .. currentmodule:: sounddevice .. autoclass:: default :members: python-sounddevice-0.5.3/doc/api/platform-specific-settings.rst000066400000000000000000000004641507516237500247020ustar00rootroot00000000000000Platform-specific Settings ========================== .. currentmodule:: sounddevice .. topic:: Overview .. autosummary:: :nosignatures: AsioSettings CoreAudioSettings WasapiSettings .. autoclass:: AsioSettings .. autoclass:: CoreAudioSettings .. autoclass:: WasapiSettings python-sounddevice-0.5.3/doc/api/raw-streams.rst000066400000000000000000000004451507516237500217010ustar00rootroot00000000000000Raw Streams =========== .. currentmodule:: sounddevice .. topic:: Overview .. autosummary:: :nosignatures: RawStream RawInputStream RawOutputStream .. autoclass:: RawStream :members: read, write .. autoclass:: RawInputStream .. autoclass:: RawOutputStream python-sounddevice-0.5.3/doc/api/streams.rst000066400000000000000000000005171507516237500211120ustar00rootroot00000000000000Streams using NumPy Arrays ========================== .. currentmodule:: sounddevice .. topic:: Overview .. autosummary:: :nosignatures: Stream InputStream OutputStream .. autoclass:: Stream :members: :undoc-members: :inherited-members: .. autoclass:: InputStream .. autoclass:: OutputStream python-sounddevice-0.5.3/doc/conf.py000066400000000000000000000051011507516237500174220ustar00rootroot00000000000000"""Configuration file for Sphinx.""" import sys import os from subprocess import check_output sys.path.insert(0, os.path.abspath('..')) sys.path.insert(0, os.path.abspath('.')) # Fake import to avoid actually loading CFFI and the PortAudio library import fake__sounddevice sys.modules['_sounddevice'] = sys.modules['fake__sounddevice'] extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.intersphinx', 'sphinx.ext.viewcode', 'sphinx.ext.napoleon', # support for NumPy-style docstrings 'sphinx_last_updated_by_git', ] autoclass_content = 'init' autodoc_member_order = 'bysource' napoleon_google_docstring = False napoleon_numpy_docstring = True napoleon_include_private_with_doc = False napoleon_include_special_with_doc = False napoleon_use_admonition_for_examples = False napoleon_use_admonition_for_notes = False napoleon_use_admonition_for_references = False napoleon_use_ivar = False napoleon_use_param = False napoleon_use_rtype = False intersphinx_mapping = { 'python': ('https://docs.python.org/3/', None), 'numpy': ('https://numpy.org/doc/stable/', None), } master_doc = 'index' authors = 'Matthias Geier' project = 'python-sounddevice' try: release = check_output(['git', 'describe', '--tags', '--always']) release = release.decode().strip() except Exception: release = '' try: today = check_output(['git', 'show', '-s', '--format=%ad', '--date=short']) today = today.decode().strip() except Exception: today = '' default_role = 'py:obj' nitpicky = True html_theme = 'insipid' html_theme_options = { } html_title = project + ', version ' + release html_favicon = 'favicon.svg' html_domain_indices = False html_show_copyright = False html_copy_source = False html_permalinks_icon = 'ยง' htmlhelp_basename = 'python-sounddevice' latex_elements = { 'papersize': 'a4paper', #'preamble': '', 'printindex': '', } latex_documents = [('index', 'python-sounddevice.tex', project, authors, 'howto')] latex_show_urls = 'footnote' latex_domain_indices = False def gh_example_role(rolename, rawtext, text, lineno, inliner, options={}, content=()): from docutils import nodes, utils github_url = 'https://github.com/spatialaudio/python-sounddevice' base_url = github_url + '/blob/' + release + '/examples/%s' text = utils.unescape(text) full_url = base_url % text pnode = nodes.reference(internal=False, refuri=full_url) pnode += nodes.literal(text, text, classes=['file']) return [pnode], [] def setup(app): app.add_role('gh-example', gh_example_role) python-sounddevice-0.5.3/doc/contributing.rst000066400000000000000000000000661507516237500213710ustar00rootroot00000000000000.. highlight:: none .. include:: ../CONTRIBUTING.rst python-sounddevice-0.5.3/doc/examples.rst000066400000000000000000000031531507516237500205000ustar00rootroot00000000000000.. include:: ../examples/README.rst Play a Sound File ----------------- :gh-example:`play_file.py` .. literalinclude:: ../examples/play_file.py Play a Very Long Sound File --------------------------- :gh-example:`play_long_file.py` .. literalinclude:: ../examples/play_long_file.py Play a Very Long Sound File without Using NumPy ----------------------------------------------- :gh-example:`play_long_file_raw.py` .. literalinclude:: ../examples/play_long_file_raw.py Play a Web Stream ----------------- :gh-example:`play_stream.py` .. literalinclude:: ../examples/play_stream.py Play a Sine Signal ------------------ :gh-example:`play_sine.py` .. literalinclude:: ../examples/play_sine.py Input to Output Pass-Through ---------------------------- :gh-example:`wire.py` .. literalinclude:: ../examples/wire.py Plot Microphone Signal(s) in Real-Time -------------------------------------- :gh-example:`plot_input.py` .. literalinclude:: ../examples/plot_input.py Real-Time Text-Mode Spectrogram ------------------------------- :gh-example:`spectrogram.py` .. literalinclude:: ../examples/spectrogram.py Recording with Arbitrary Duration --------------------------------- :gh-example:`rec_unlimited.py` .. literalinclude:: ../examples/rec_unlimited.py Using a stream in an `asyncio` coroutine ---------------------------------------- :gh-example:`asyncio_coroutines.py` .. literalinclude:: ../examples/asyncio_coroutines.py Creating an `asyncio` generator for audio blocks ------------------------------------------------ :gh-example:`asyncio_generators.py` .. literalinclude:: ../examples/asyncio_generators.py python-sounddevice-0.5.3/doc/fake__sounddevice.py000066400000000000000000000016361507516237500221430ustar00rootroot00000000000000"""Mock module for Sphinx autodoc.""" import ctypes.util old_find_library = ctypes.util.find_library def new_find_library(name): if 'portaudio' in name.lower(): return NotImplemented return old_find_library(name) # Monkey-patch ctypes to disable searching for PortAudio ctypes.util.find_library = new_find_library class ffi: NULL = NotImplemented I_AM_FAKE = True # This is used for the documentation of "default" def dlopen(self, _): return FakeLibrary() ffi = ffi() class FakeLibrary: # from portaudio.h: paFloat32 = paInt32 = paInt24 = paInt16 = paInt8 = paUInt8 = NotImplemented paFramesPerBufferUnspecified = 0 def Pa_Initialize(self): return 0 def Pa_Terminate(self): return 0 # from stdio.h: def fopen(*args, **kwargs): return NotImplemented def fclose(*args): pass stderr = NotImplemented python-sounddevice-0.5.3/doc/favicon.svg000066400000000000000000000054631507516237500203040ustar00rootroot00000000000000 python-sounddevice-0.5.3/doc/index.rst000066400000000000000000000030571507516237500177740ustar00rootroot00000000000000.. include:: ../README.rst ---- .. raw:: html
click here to see full table of contents .. toctree:: installation usage examples contributing api/index version-history .. only:: html :ref:`genindex` .. raw:: html
.. only:: html .. admonition:: How To Navigate This Site Use the *next* and *previous* links at the top and the bottom of each page to flip through the pages. Alternatively, you can use the right and left arrow keys on your keyboard. Some additional keyboard shortcuts are provided via the `accesskey feature`__: :kbd:`n` next, :kbd:`p` previous, :kbd:`u` up (= to the parent page), :kbd:`i` index, :kbd:`s` search and :kbd:`m` menu (= open/close sidebar). __ https://developer.mozilla.org/en-US/docs/ Web/HTML/Global_attributes/accesskey Click on the `hamburger button`__ in the topbar to open and close the sidebar. The width of the sidebar can be adjusted by dragging its border. Click on the title in the topbar to scroll to the top of the page, if already at the top, go "up" to the parent page (eventually ending up on this very page). __ https://en.wikipedia.org/wiki/Hamburger_button On *touch-enabled* devices: Tap at the top of the page to show the topbar (if it was scrolled away); swipe from the left edge to show the sidebar, swipe towards the left to hide it. python-sounddevice-0.5.3/doc/installation.rst000066400000000000000000000104661507516237500213700ustar00rootroot00000000000000Installation ============ First of all, you'll need Python_. There are many distributions of Python available, anyone where CFFI_ is supported should work. You can get the latest ``sounddevice`` release from PyPI_ (using ``pip``). But first, it is recommended to create a virtual environment (e.g. using `python3 -m venv`__ or `conda create`__). After activating the environment, the ``sounddevice`` module can be installed with:: python -m pip install sounddevice __ https://docs.python.org/3/library/venv.html __ https://docs.conda.io/projects/conda/en/latest/user-guide/getting-started.html#creating-environments If you have already installed an old version of the module in the environment, you can use the ``--upgrade`` flag to get the newest release. To un-install, use:: python -m pip uninstall sounddevice If you want to try the very latest development version of the ``sounddevice`` module, have a look at the section about :doc:`contributing`. If you install the ``sounddevice`` module with ``pip`` on macOS or Windows, the PortAudio_ library will be installed automagically. On other platforms, you might have to install PortAudio with your package manager (the package might be called ``libportaudio2`` or similar). .. note:: If you install PortAudio with a package manager (including ``conda``), it will likely override the version installed with ``pip``. The NumPy_ library is only needed if you want to play back and record NumPy arrays. The classes `sounddevice.RawStream`, `sounddevice.RawInputStream` and `sounddevice.RawOutputStream` use plain Python buffer objects and don't need NumPy at all. If needed -- and not installed already -- NumPy can be installed like this:: python -m pip install numpy ASIO Support ------------ Installing the ``sounddevice`` module with ``pip`` (on Windows) will provide two PortAudio_ DLLs, with and without ASIO support. By default, the DLL *without* ASIO support is loaded (because of the problems mentioned in `issue #496`__). To load the DLL *with* ASIO support, the environment variable ``SD_ENABLE_ASIO`` has to be set *before* importing the ``sounddevice`` module, for example like this: .. code:: python import os # Set environment variable before importing sounddevice. Value is not important. os.environ["SD_ENABLE_ASIO"] = "1" import sounddevice as sd print(sd.query_hostapis()) __ https://github.com/spatialaudio/python-sounddevice/issues/496 .. note:: This will only work if the ``sounddevice`` module has been installed via ``pip``. This will not work with the ``conda`` package (see below). .. note:: This will not work if a custom ``portaudio.dll`` is present in the ``%PATH%`` (as described in the following section). Custom PortAudio Library ------------------------ If you want to use a different version of the PortAudio library (maybe a development version or a version with different features selected), you can rename the library to ``libportaudio.so`` (Linux) or ``libportaudio.dylib`` (macOS) and move it to ``/usr/local/lib``. On Linux, you might have to run ``sudo ldconfig`` after that, for the library to be found. On Windows, you can rename the library to ``portaudio.dll`` and move it to any directory in your ``%PATH%``. In case of doubt you should create a fresh directory for your library and add that to your ``PATH`` variable. Alternative Packages -------------------- If you are using the ``conda`` package manager (e.g. with miniforge_), you can install the ``sounddevice`` module from the ``conda-forge`` channel:: conda install -c conda-forge python-sounddevice You can of course also use ``mamba`` if ``conda`` is too slow. .. note:: The PortAudio package on ``conda-forge`` doesn't have ASIO support, see https://github.com/conda-forge/portaudio-feedstock/issues/9. There are also packages for several other package managers: .. only:: html .. image:: https://repology.org/badge/vertical-allrepos/python:sounddevice.svg :target: https://repology.org/metapackage/python:sounddevice .. only:: latex https://repology.org/metapackage/python:sounddevice .. _PortAudio: http://www.portaudio.com/ .. _NumPy: https://numpy.org/ .. _Python: https://www.python.org/ .. _miniforge: https://github.com/conda-forge/miniforge .. _CFFI: https://cffi.readthedocs.io/ .. _PyPI: https://pypi.org/project/sounddevice/ python-sounddevice-0.5.3/doc/requirements.txt000066400000000000000000000000621507516237500214100ustar00rootroot00000000000000insipid-sphinx-theme sphinx-last-updated-by-git python-sounddevice-0.5.3/doc/usage.rst000066400000000000000000000137041507516237500177710ustar00rootroot00000000000000.. currentmodule:: sounddevice Usage ===== First, import the module: .. code:: python import sounddevice as sd 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 `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 `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 `default.samplerate`: .. code:: python sd.default.samplerate = fs After that, you can drop the *samplerate* argument: .. code:: python 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, 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 `default`: .. code:: python sd.default.samplerate = fs sd.default.channels = 2 After that, you can drop the additional arguments: .. code:: python 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 `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. 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(int(duration * fs), dtype='float64') Simultaneous Playback and Recording ----------------------------------- 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. Again, default values can be used: .. code:: python sd.default.samplerate = fs sd.default.channels = 2 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 `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 `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 `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 `default.device` for details. .. code:: python import sounddevice as sd sd.default.samplerate = 44100 sd.default.device = 'digital output' sd.play(myarray) Callback Streams ---------------- 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 import sounddevice as sd duration = 5.5 # seconds def callback(indata, outdata, frames, time, status): if status: print(status) outdata[:] = indata with sd.Stream(channels=2, callback=callback): sd.sleep(int(duration * 1000)) The same thing can be done with `RawStream` (NumPy_ doesn't have to be installed): .. code:: python import sounddevice as sd duration = 5.5 # seconds def callback(indata, outdata, frames, time, status): if status: print(status) outdata[:] = indata with sd.RawStream(channels=2, dtype='int24', callback=callback): sd.sleep(int(duration * 1000)) .. 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 `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/ python-sounddevice-0.5.3/doc/version-history.rst000066400000000000000000000001321507516237500220400ustar00rootroot00000000000000Version History =============== .. currentmodule:: sounddevice .. include:: ../NEWS.rst python-sounddevice-0.5.3/examples/000077500000000000000000000000001507516237500171775ustar00rootroot00000000000000python-sounddevice-0.5.3/examples/README.rst000066400000000000000000000003711507516237500206670ustar00rootroot00000000000000Example Programs ================ Most of these examples use the `argparse` module to handle command line arguments. To show a help text explaining all available arguments, use the ``--help`` argument. For example:: python play_file.py --help python-sounddevice-0.5.3/examples/asyncio_coroutines.py000077500000000000000000000042241507516237500234750ustar00rootroot00000000000000#!/usr/bin/env python3 """An example for using a stream in an asyncio coroutine. This example shows how to create a stream in a coroutine and how to wait for the completion of the stream. You need Python 3.7 or newer to run this. """ import asyncio import sys import numpy as np import sounddevice as sd async def record_buffer(buffer, **kwargs): loop = asyncio.get_event_loop() event = asyncio.Event() idx = 0 def callback(indata, frame_count, time_info, status): nonlocal idx if status: print(status) remainder = len(buffer) - idx if remainder == 0: loop.call_soon_threadsafe(event.set) raise sd.CallbackStop indata = indata[:remainder] buffer[idx:idx + len(indata)] = indata idx += len(indata) stream = sd.InputStream(callback=callback, dtype=buffer.dtype, channels=buffer.shape[1], **kwargs) with stream: await event.wait() async def play_buffer(buffer, **kwargs): loop = asyncio.get_event_loop() event = asyncio.Event() idx = 0 def callback(outdata, frame_count, time_info, status): nonlocal idx if status: print(status) remainder = len(buffer) - idx if remainder == 0: loop.call_soon_threadsafe(event.set) raise sd.CallbackStop valid_frames = frame_count if remainder >= frame_count else remainder outdata[:valid_frames] = buffer[idx:idx + valid_frames] outdata[valid_frames:] = 0 idx += valid_frames stream = sd.OutputStream(callback=callback, dtype=buffer.dtype, channels=buffer.shape[1], **kwargs) with stream: await event.wait() async def main(frames=150_000, channels=1, dtype='float32', **kwargs): buffer = np.empty((frames, channels), dtype=dtype) print('recording buffer ...') await record_buffer(buffer, **kwargs) print('playing buffer ...') await play_buffer(buffer, **kwargs) print('done') if __name__ == "__main__": try: asyncio.run(main()) except KeyboardInterrupt: sys.exit('\nInterrupted by user') python-sounddevice-0.5.3/examples/asyncio_generators.py000077500000000000000000000064751507516237500234660ustar00rootroot00000000000000#!/usr/bin/env python3 """Creating an asyncio generator for blocks of audio data. This example shows how a generator can be used to analyze audio input blocks. In addition, it shows how a generator can be created that yields not only input blocks but also output blocks where audio data can be written to. You need Python 3.7 or newer to run this. """ import asyncio import queue import sys import numpy as np import sounddevice as sd async def inputstream_generator(channels=1, **kwargs): """Generator that yields blocks of input data as NumPy arrays.""" q_in = asyncio.Queue() loop = asyncio.get_event_loop() def callback(indata, frame_count, time_info, status): loop.call_soon_threadsafe(q_in.put_nowait, (indata.copy(), status)) stream = sd.InputStream(callback=callback, channels=channels, **kwargs) with stream: while True: indata, status = await q_in.get() yield indata, status async def stream_generator(blocksize, *, channels=1, dtype='float32', pre_fill_blocks=10, **kwargs): """Generator that yields blocks of input/output data as NumPy arrays. The output blocks are uninitialized and have to be filled with appropriate audio signals. """ assert blocksize != 0 q_in = asyncio.Queue() q_out = queue.Queue() loop = asyncio.get_event_loop() def callback(indata, outdata, frame_count, time_info, status): loop.call_soon_threadsafe(q_in.put_nowait, (indata.copy(), status)) outdata[:] = q_out.get_nowait() # pre-fill output queue for _ in range(pre_fill_blocks): q_out.put(np.zeros((blocksize, channels), dtype=dtype)) stream = sd.Stream(blocksize=blocksize, callback=callback, dtype=dtype, channels=channels, **kwargs) with stream: while True: indata, status = await q_in.get() outdata = np.empty((blocksize, channels), dtype=dtype) yield indata, outdata, status q_out.put_nowait(outdata) async def print_input_infos(**kwargs): """Show minimum and maximum value of each incoming audio block.""" async for indata, status in inputstream_generator(**kwargs): if status: print(status) print('min:', indata.min(), '\t', 'max:', indata.max()) async def wire_coro(**kwargs): """Create a connection between audio inputs and outputs. Asynchronously iterates over a stream generator and for each block simply copies the input data into the output block. """ async for indata, outdata, status in stream_generator(**kwargs): if status: print(status) outdata[:] = indata async def main(**kwargs): print('Some information about the input signal:') try: await asyncio.wait_for(print_input_infos(), timeout=2) except asyncio.TimeoutError: pass print('\nEnough of that, activating wire ...\n') audio_task = asyncio.create_task(wire_coro(**kwargs)) for i in range(10, 0, -1): print(i) await asyncio.sleep(1) audio_task.cancel() try: await audio_task except asyncio.CancelledError: print('\nwire was cancelled') if __name__ == "__main__": try: asyncio.run(main(blocksize=1024)) except KeyboardInterrupt: sys.exit('\nInterrupted by user') python-sounddevice-0.5.3/examples/play_file.py000077500000000000000000000045401507516237500215230ustar00rootroot00000000000000#!/usr/bin/env python3 """Load an audio file into memory and play its contents. NumPy and the soundfile module (https://python-soundfile.readthedocs.io/) must be installed for this to work. This example program loads the whole file into memory before starting playback. To play very long files, you should use play_long_file.py instead. This example could simply be implemented like this:: import sounddevice as sd import soundfile as sf data, fs = sf.read('my-file.wav') sd.play(data, fs) sd.wait() ... but in this example we show a more low-level implementation using a callback stream. """ import argparse import threading import sounddevice as sd import soundfile as sf def int_or_str(text): """Helper function for argument parsing.""" try: return int(text) except ValueError: return text parser = argparse.ArgumentParser(add_help=False) parser.add_argument( '-l', '--list-devices', action='store_true', help='show list of audio devices and exit') args, remaining = parser.parse_known_args() if args.list_devices: print(sd.query_devices()) parser.exit(0) parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, parents=[parser]) parser.add_argument( 'filename', metavar='FILENAME', help='audio file to be played back') parser.add_argument( '-d', '--device', type=int_or_str, help='output device (numeric ID or substring)') args = parser.parse_args(remaining) event = threading.Event() try: data, fs = sf.read(args.filename, always_2d=True) current_frame = 0 def callback(outdata, frames, time, status): global current_frame if status: print(status) chunksize = min(len(data) - current_frame, frames) outdata[:chunksize] = data[current_frame:current_frame + chunksize] if chunksize < frames: outdata[chunksize:] = 0 raise sd.CallbackStop() current_frame += chunksize stream = sd.OutputStream( samplerate=fs, device=args.device, channels=data.shape[1], callback=callback, finished_callback=event.set) with stream: event.wait() # Wait until playback is finished except KeyboardInterrupt: parser.exit(1, '\nInterrupted by user') except Exception as e: parser.exit(1, type(e).__name__ + ': ' + str(e)) python-sounddevice-0.5.3/examples/play_long_file.py000077500000000000000000000066321507516237500225460ustar00rootroot00000000000000#!/usr/bin/env python3 """Play an audio file using a limited amount of memory. The soundfile module (https://python-soundfile.readthedocs.io/) must be installed for this to work. In contrast to play_file.py, which loads the whole file into memory before starting playback, this example program only holds a given number of audio blocks in memory and is therefore able to play files that are larger than the available RAM. This example is implemented using NumPy, see play_long_file_raw.py for a version that doesn't need NumPy. """ import argparse import queue import sys import threading import sounddevice as sd import soundfile as sf def int_or_str(text): """Helper function for argument parsing.""" try: return int(text) except ValueError: return text parser = argparse.ArgumentParser(add_help=False) parser.add_argument( '-l', '--list-devices', action='store_true', help='show list of audio devices and exit') args, remaining = parser.parse_known_args() if args.list_devices: print(sd.query_devices()) parser.exit(0) parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, parents=[parser]) parser.add_argument( 'filename', metavar='FILENAME', help='audio file to be played back') parser.add_argument( '-d', '--device', type=int_or_str, help='output device (numeric ID or substring)') parser.add_argument( '-b', '--blocksize', type=int, default=2048, help='block size (default: %(default)s)') parser.add_argument( '-q', '--buffersize', type=int, default=20, help='number of blocks used for buffering (default: %(default)s)') args = parser.parse_args(remaining) if args.blocksize == 0: parser.error('blocksize must not be zero') if args.buffersize < 1: parser.error('buffersize must be at least 1') q = queue.Queue(maxsize=args.buffersize) event = threading.Event() def callback(outdata, frames, time, status): assert frames == args.blocksize if status.output_underflow: print('Output underflow: increase blocksize?', file=sys.stderr) raise sd.CallbackAbort assert not status try: data = q.get_nowait() except queue.Empty as e: print('Buffer is empty: increase buffersize?', file=sys.stderr) raise sd.CallbackAbort from e if len(data) < len(outdata): outdata[:len(data)] = data outdata[len(data):].fill(0) raise sd.CallbackStop else: outdata[:] = data try: with sf.SoundFile(args.filename) as f: for _ in range(args.buffersize): data = f.read(args.blocksize) if not len(data): break q.put_nowait(data) # Pre-fill queue stream = sd.OutputStream( samplerate=f.samplerate, blocksize=args.blocksize, device=args.device, channels=f.channels, callback=callback, finished_callback=event.set) with stream: timeout = args.blocksize * args.buffersize / f.samplerate while len(data): data = f.read(args.blocksize) q.put(data, timeout=timeout) event.wait() # Wait until playback is finished except KeyboardInterrupt: parser.exit(1, '\nInterrupted by user') except queue.Full: # A timeout occurred, i.e. there was an error in the callback parser.exit(1) except Exception as e: parser.exit(1, type(e).__name__ + ': ' + str(e)) python-sounddevice-0.5.3/examples/play_long_file_raw.py000077500000000000000000000061741507516237500234200ustar00rootroot00000000000000#!/usr/bin/env python3 """Play an audio file using a limited amount of memory. This is the same as play_long_file.py, but implemented without using NumPy. """ import argparse import queue import sys import threading import sounddevice as sd import soundfile as sf def int_or_str(text): """Helper function for argument parsing.""" try: return int(text) except ValueError: return text parser = argparse.ArgumentParser(add_help=False) parser.add_argument( '-l', '--list-devices', action='store_true', help='show list of audio devices and exit') args, remaining = parser.parse_known_args() if args.list_devices: print(sd.query_devices()) parser.exit(0) parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, parents=[parser]) parser.add_argument( 'filename', metavar='FILENAME', help='audio file to be played back') parser.add_argument( '-d', '--device', type=int_or_str, help='output device (numeric ID or substring)') parser.add_argument( '-b', '--blocksize', type=int, default=2048, help='block size (default: %(default)s)') parser.add_argument( '-q', '--buffersize', type=int, default=20, help='number of blocks used for buffering (default: %(default)s)') args = parser.parse_args(remaining) if args.blocksize == 0: parser.error('blocksize must not be zero') if args.buffersize < 1: parser.error('buffersize must be at least 1') q = queue.Queue(maxsize=args.buffersize) event = threading.Event() def callback(outdata, frames, time, status): assert frames == args.blocksize if status.output_underflow: print('Output underflow: increase blocksize?', file=sys.stderr) raise sd.CallbackAbort assert not status try: data = q.get_nowait() except queue.Empty as e: print('Buffer is empty: increase buffersize?', file=sys.stderr) raise sd.CallbackAbort from e if len(data) < len(outdata): outdata[:len(data)] = data outdata[len(data):] = b'\x00' * (len(outdata) - len(data)) raise sd.CallbackStop else: outdata[:] = data try: with sf.SoundFile(args.filename) as f: for _ in range(args.buffersize): data = f.buffer_read(args.blocksize, dtype='float32') if not data: break q.put_nowait(data) # Pre-fill queue stream = sd.RawOutputStream( samplerate=f.samplerate, blocksize=args.blocksize, device=args.device, channels=f.channels, dtype='float32', callback=callback, finished_callback=event.set) with stream: timeout = args.blocksize * args.buffersize / f.samplerate while data: data = f.buffer_read(args.blocksize, dtype='float32') q.put(data, timeout=timeout) event.wait() # Wait until playback is finished except KeyboardInterrupt: parser.exit(1, '\nInterrupted by user') except queue.Full: # A timeout occurred, i.e. there was an error in the callback parser.exit(1) except Exception as e: parser.exit(1, type(e).__name__ + ': ' + str(e)) python-sounddevice-0.5.3/examples/play_sine.py000077500000000000000000000035611507516237500215440ustar00rootroot00000000000000#!/usr/bin/env python3 """Play a sine signal.""" import argparse import sys import numpy as np import sounddevice as sd def int_or_str(text): """Helper function for argument parsing.""" try: return int(text) except ValueError: return text parser = argparse.ArgumentParser(add_help=False) parser.add_argument( '-l', '--list-devices', action='store_true', help='show list of audio devices and exit') args, remaining = parser.parse_known_args() if args.list_devices: print(sd.query_devices()) parser.exit(0) parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, parents=[parser]) parser.add_argument( 'frequency', nargs='?', metavar='FREQUENCY', type=float, default=500, help='frequency in Hz (default: %(default)s)') parser.add_argument( '-d', '--device', type=int_or_str, help='output device (numeric ID or substring)') parser.add_argument( '-a', '--amplitude', type=float, default=0.2, help='amplitude (default: %(default)s)') args = parser.parse_args(remaining) start_idx = 0 try: samplerate = sd.query_devices(args.device, 'output')['default_samplerate'] def callback(outdata, frames, time, status): if status: print(status, file=sys.stderr) global start_idx t = (start_idx + np.arange(frames)) / samplerate t = t.reshape(-1, 1) outdata[:] = args.amplitude * np.sin(2 * np.pi * args.frequency * t) start_idx += frames with sd.OutputStream(device=args.device, channels=1, callback=callback, samplerate=samplerate): print('#' * 80) print('press Return to quit') print('#' * 80) input() except KeyboardInterrupt: parser.exit(1, '\nInterrupted by user') except Exception as e: parser.exit(1, type(e).__name__ + ': ' + str(e)) python-sounddevice-0.5.3/examples/play_stream.py000077500000000000000000000070401507516237500220750ustar00rootroot00000000000000#!/usr/bin/env python3 """Play a web stream. ffmpeg-python (https://github.com/kkroening/ffmpeg-python) has to be installed. If you don't know a stream URL, try http://icecast.spc.org:8000/longplayer (see https://longplayer.org/ for a description). """ import argparse import queue import sys import ffmpeg import sounddevice as sd def int_or_str(text): """Helper function for argument parsing.""" try: return int(text) except ValueError: return text parser = argparse.ArgumentParser(add_help=False) parser.add_argument( '-l', '--list-devices', action='store_true', help='show list of audio devices and exit') args, remaining = parser.parse_known_args() if args.list_devices: print(sd.query_devices()) parser.exit(0) parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, parents=[parser]) parser.add_argument( 'url', metavar='URL', help='stream URL') parser.add_argument( '-d', '--device', type=int_or_str, help='output device (numeric ID or substring)') parser.add_argument( '-b', '--blocksize', type=int, default=1024, help='block size (default: %(default)s)') parser.add_argument( '-q', '--buffersize', type=int, default=20, help='number of blocks used for buffering (default: %(default)s)') args = parser.parse_args(remaining) if args.blocksize == 0: parser.error('blocksize must not be zero') if args.buffersize < 1: parser.error('buffersize must be at least 1') q = queue.Queue(maxsize=args.buffersize) print('Getting stream information ...') try: info = ffmpeg.probe(args.url) except ffmpeg.Error as e: sys.stderr.buffer.write(e.stderr) parser.exit(1, str(e)) streams = info.get('streams', []) if len(streams) != 1: parser.exit(1, 'There must be exactly one stream available') stream = streams[0] if stream.get('codec_type') != 'audio': parser.exit(1, 'The stream must be an audio stream') channels = stream['channels'] samplerate = float(stream['sample_rate']) def callback(outdata, frames, time, status): assert frames == args.blocksize if status.output_underflow: print('Output underflow: increase blocksize?', file=sys.stderr) raise sd.CallbackAbort assert not status try: data = q.get_nowait() except queue.Empty as e: print('Buffer is empty: increase buffersize?', file=sys.stderr) raise sd.CallbackAbort from e assert len(data) == len(outdata) outdata[:] = data try: print('Opening stream ...') process = ffmpeg.input( args.url ).output( 'pipe:', format='f32le', acodec='pcm_f32le', ac=channels, ar=samplerate, loglevel='quiet', ).run_async(pipe_stdout=True) stream = sd.RawOutputStream( samplerate=samplerate, blocksize=args.blocksize, device=args.device, channels=channels, dtype='float32', callback=callback) read_size = args.blocksize * channels * stream.samplesize print('Buffering ...') for _ in range(args.buffersize): q.put_nowait(process.stdout.read(read_size)) print('Starting Playback ...') with stream: timeout = args.blocksize * args.buffersize / samplerate while True: q.put(process.stdout.read(read_size), timeout=timeout) except KeyboardInterrupt: parser.exit(1, '\nInterrupted by user') except queue.Full: # A timeout occurred, i.e. there was an error in the callback parser.exit(1) except Exception as e: parser.exit(1, type(e).__name__ + ': ' + str(e)) python-sounddevice-0.5.3/examples/plot_input.py000077500000000000000000000074711507516237500217620ustar00rootroot00000000000000#!/usr/bin/env python3 """Plot the live microphone signal(s) with matplotlib. Matplotlib and NumPy have to be installed. """ import argparse import queue import sys from matplotlib.animation import FuncAnimation import matplotlib.pyplot as plt import numpy as np import sounddevice as sd def int_or_str(text): """Helper function for argument parsing.""" try: return int(text) except ValueError: return text parser = argparse.ArgumentParser(add_help=False) parser.add_argument( '-l', '--list-devices', action='store_true', help='show list of audio devices and exit') args, remaining = parser.parse_known_args() if args.list_devices: print(sd.query_devices()) parser.exit(0) parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, parents=[parser]) parser.add_argument( 'channels', type=int, default=[1], nargs='*', metavar='CHANNEL', help='input channels to plot (default: the first)') parser.add_argument( '-d', '--device', type=int_or_str, help='input device (numeric ID or substring)') parser.add_argument( '-w', '--window', type=float, default=200, metavar='DURATION', help='visible time slot (default: %(default)s ms)') parser.add_argument( '-i', '--interval', type=float, default=30, help='minimum time between plot updates (default: %(default)s ms)') parser.add_argument( '-b', '--blocksize', type=int, help='block size (in samples)') parser.add_argument( '-r', '--samplerate', type=float, help='sampling rate of audio device') parser.add_argument( '-n', '--downsample', type=int, default=10, metavar='N', help='display every Nth sample (default: %(default)s)') args = parser.parse_args(remaining) if any(c < 1 for c in args.channels): parser.error('argument CHANNEL: must be >= 1') mapping = [c - 1 for c in args.channels] # Channel numbers start with 1 q = queue.Queue() def audio_callback(indata, frames, time, status): """This is called (from a separate thread) for each audio block.""" if status: print(status, file=sys.stderr) # Fancy indexing with mapping creates a (necessary!) copy: q.put(indata[::args.downsample, mapping]) def update_plot(frame): """This is called by matplotlib for each plot update. Typically, audio callbacks happen more frequently than plot updates, therefore the queue tends to contain multiple blocks of audio data. """ global plotdata while True: try: data = q.get_nowait() except queue.Empty: break shift = len(data) plotdata = np.roll(plotdata, -shift, axis=0) plotdata[-shift:, :] = data for column, line in enumerate(lines): line.set_ydata(plotdata[:, column]) return lines try: if args.samplerate is None: device_info = sd.query_devices(args.device, 'input') args.samplerate = device_info['default_samplerate'] length = int(args.window * args.samplerate / (1000 * args.downsample)) plotdata = np.zeros((length, len(args.channels))) fig, ax = plt.subplots() lines = ax.plot(plotdata) if len(args.channels) > 1: ax.legend([f'channel {c}' for c in args.channels], loc='lower left', ncol=len(args.channels)) ax.axis((0, len(plotdata), -1, 1)) ax.set_yticks([0]) ax.yaxis.grid(True) ax.tick_params(bottom=False, top=False, labelbottom=False, right=False, left=False, labelleft=False) fig.tight_layout(pad=0) stream = sd.InputStream( device=args.device, channels=max(args.channels), samplerate=args.samplerate, callback=audio_callback) ani = FuncAnimation(fig, update_plot, interval=args.interval, blit=True) with stream: plt.show() except Exception as e: parser.exit(1, type(e).__name__ + ': ' + str(e)) python-sounddevice-0.5.3/examples/priming_output.py000077500000000000000000000014311507516237500226400ustar00rootroot00000000000000#!/usr/bin/env python3 """Test priming output buffer. See http://www.portaudio.com/docs/proposals/020-AllowCallbackToPrimeStream.html Note that this is only supported in some of the host APIs. """ import sounddevice as sd def callback(indata, outdata, frames, time, status): outdata.fill(0) if status.priming_output: assert status.input_underflow, 'input underflow flag should be set' assert not indata.any(), 'input buffer should be filled with zeros' print('Priming output buffer!') outdata[0] = 1 else: print('Not priming, I quit!') raise sd.CallbackStop with sd.Stream(channels=2, callback=callback, prime_output_buffers_using_stream_callback=True) as stream: while stream.active: sd.sleep(100) python-sounddevice-0.5.3/examples/rec_gui.py000077500000000000000000000167251507516237500212040ustar00rootroot00000000000000#!/usr/bin/env python3 """Simple GUI for recording into a WAV file. There are 3 concurrent activities: GUI, audio callback, file-writing thread. Neither the GUI nor the audio callback is supposed to block. Blocking in any of the GUI functions could make the GUI "freeze", blocking in the audio callback could lead to drop-outs in the recording. Blocking the file-writing thread for some time is no problem, as long as the recording can be stopped successfully when it is supposed to. """ import contextlib import queue import tempfile import threading import tkinter as tk from tkinter import ttk from tkinter.simpledialog import Dialog import numpy as np import sounddevice as sd import soundfile as sf def file_writing_thread(*, q, **soundfile_args): """Write data from queue to file until *None* is received.""" # NB: If you want fine-grained control about the buffering of the file, you # can use Python's open() function (with the "buffering" argument) and # pass the resulting file object to sf.SoundFile(). with sf.SoundFile(**soundfile_args) as f: while True: data = q.get() if data is None: break f.write(data) class SettingsWindow(Dialog): """Dialog window for choosing sound device.""" def body(self, master): ttk.Label(master, text='Select host API:').pack(anchor='w') self.hostapi_list = ttk.Combobox(master, state='readonly', width=50) self.hostapi_list.pack() self.hostapi_list['values'] = [ hostapi['name'] for hostapi in sd.query_hostapis()] ttk.Label(master, text='Select sound device:').pack(anchor='w') self.device_ids = [] self.device_list = ttk.Combobox(master, state='readonly', width=50) self.device_list.pack() self.hostapi_list.bind('<>', self.update_device_list) with contextlib.suppress(sd.PortAudioError): self.hostapi_list.current(sd.default.hostapi) self.hostapi_list.event_generate('<>') def update_device_list(self, *args): hostapi = sd.query_hostapis(self.hostapi_list.current()) self.device_ids = [ idx for idx in hostapi['devices'] if sd.query_devices(idx)['max_input_channels'] > 0] self.device_list['values'] = [ sd.query_devices(idx)['name'] for idx in self.device_ids] default = hostapi['default_input_device'] if default >= 0: self.device_list.current(self.device_ids.index(default)) def validate(self): self.result = self.device_ids[self.device_list.current()] return True class RecGui(tk.Tk): stream = None def __init__(self): super().__init__() self.title('Recording GUI') padding = 10 f = ttk.Frame() self.rec_button = ttk.Button(f) self.rec_button.pack(side='left', padx=padding, pady=padding) self.settings_button = ttk.Button( f, text='settings', command=self.on_settings) self.settings_button.pack(side='left', padx=padding, pady=padding) f.pack(expand=True, padx=padding, pady=padding) self.file_label = ttk.Label(text='') self.file_label.pack(anchor='w') self.input_overflows = 0 self.status_label = ttk.Label() self.status_label.pack(anchor='w') self.meter = ttk.Progressbar() self.meter['orient'] = 'horizontal' self.meter['mode'] = 'determinate' self.meter['maximum'] = 1.0 self.meter.pack(fill='x') # We try to open a stream with default settings first, if that doesn't # work, the user can manually change the device(s) self.create_stream() self.recording = self.previously_recording = False self.audio_q = queue.Queue() self.peak = 0 self.metering_q = queue.Queue(maxsize=1) self.protocol('WM_DELETE_WINDOW', self.close_window) self.init_buttons() self.update_gui() def create_stream(self, device=None): if self.stream is not None: self.stream.close() self.stream = sd.InputStream( device=device, channels=1, callback=self.audio_callback) self.stream.start() def audio_callback(self, indata, frames, time, status): """This is called (from a separate thread) for each audio block.""" if status.input_overflow: # NB: This increment operation is not atomic, but this doesn't # matter since no other thread is writing to the attribute. self.input_overflows += 1 # NB: self.recording is accessed from different threads. # This is safe because here we are only accessing it once (with a # single bytecode instruction). if self.recording: self.audio_q.put(indata.copy()) self.previously_recording = True else: if self.previously_recording: self.audio_q.put(None) self.previously_recording = False self.peak = max(self.peak, np.max(np.abs(indata))) try: self.metering_q.put_nowait(self.peak) except queue.Full: pass else: self.peak = 0 def on_rec(self): self.settings_button['state'] = 'disabled' self.recording = True filename = tempfile.mktemp( prefix='delme_rec_gui_', suffix='.wav', dir='') if self.audio_q.qsize() != 0: print('WARNING: Queue not empty!') self.thread = threading.Thread( target=file_writing_thread, kwargs=dict( file=filename, mode='x', samplerate=int(self.stream.samplerate), channels=self.stream.channels, q=self.audio_q, ), ) self.thread.start() # NB: File creation might fail! For brevity, we don't check for this. self.rec_button['text'] = 'stop' self.rec_button['command'] = self.on_stop self.rec_button['state'] = 'normal' self.file_label['text'] = filename def on_stop(self, *args): self.rec_button['state'] = 'disabled' self.recording = False self.wait_for_thread() def wait_for_thread(self): # NB: Waiting time could be calculated based on stream.latency self.after(10, self._wait_for_thread) def _wait_for_thread(self): if self.thread.is_alive(): self.wait_for_thread() return self.thread.join() self.init_buttons() def on_settings(self, *args): w = SettingsWindow(self, 'Settings') if w.result is not None: self.create_stream(device=w.result) def init_buttons(self): self.rec_button['text'] = 'record' self.rec_button['command'] = self.on_rec if self.stream: self.rec_button['state'] = 'normal' self.settings_button['state'] = 'normal' def update_gui(self): self.status_label['text'] = 'input overflows: {}'.format( self.input_overflows) try: peak = self.metering_q.get_nowait() except queue.Empty: pass else: self.meter['value'] = peak self.after(100, self.update_gui) def close_window(self): if self.recording: self.on_stop() self.destroy() def main(): app = RecGui() app.mainloop() if __name__ == '__main__': main() python-sounddevice-0.5.3/examples/rec_unlimited.py000077500000000000000000000054221507516237500224020ustar00rootroot00000000000000#!/usr/bin/env python3 """Create a recording with arbitrary duration. The soundfile module (https://python-soundfile.readthedocs.io/) has to be installed! """ import argparse import tempfile import queue import sys import sounddevice as sd import soundfile as sf import numpy # Make sure NumPy is loaded before it is used in the callback assert numpy # avoid "imported but unused" message (W0611) def int_or_str(text): """Helper function for argument parsing.""" try: return int(text) except ValueError: return text parser = argparse.ArgumentParser(add_help=False) parser.add_argument( '-l', '--list-devices', action='store_true', help='show list of audio devices and exit') args, remaining = parser.parse_known_args() if args.list_devices: print(sd.query_devices()) parser.exit(0) parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, parents=[parser]) parser.add_argument( 'filename', nargs='?', metavar='FILENAME', help='audio file to store recording to') parser.add_argument( '-d', '--device', type=int_or_str, help='input device (numeric ID or substring)') parser.add_argument( '-r', '--samplerate', type=int, help='sampling rate') parser.add_argument( '-c', '--channels', type=int, default=1, help='number of input channels') parser.add_argument( '-t', '--subtype', type=str, help='sound file subtype (e.g. "PCM_24")') args = parser.parse_args(remaining) q = queue.Queue() def callback(indata, frames, time, status): """This is called (from a separate thread) for each audio block.""" if status: print(status, file=sys.stderr) q.put(indata.copy()) try: if args.samplerate is None: device_info = sd.query_devices(args.device, 'input') # soundfile expects an int, sounddevice provides a float: args.samplerate = int(device_info['default_samplerate']) if args.filename is None: args.filename = tempfile.mktemp(prefix='delme_rec_unlimited_', suffix='.wav', dir='') # Make sure the file is opened before recording anything: with sf.SoundFile(args.filename, mode='x', samplerate=args.samplerate, channels=args.channels, subtype=args.subtype) as file: with sd.InputStream(samplerate=args.samplerate, device=args.device, channels=args.channels, callback=callback): print('#' * 80) print('press Ctrl+C to stop the recording') print('#' * 80) while True: file.write(q.get()) except KeyboardInterrupt: print('\nRecording finished: ' + repr(args.filename)) parser.exit(0) except Exception as e: parser.exit(1, type(e).__name__ + ': ' + str(e)) python-sounddevice-0.5.3/examples/spectrogram.py000077500000000000000000000072161507516237500221100ustar00rootroot00000000000000#!/usr/bin/env python3 """Show a text-mode spectrogram using live microphone data.""" import argparse import math import shutil import numpy as np import sounddevice as sd usage_line = ' press to quit, + or - to change scaling ' def int_or_str(text): """Helper function for argument parsing.""" try: return int(text) except ValueError: return text try: columns, _ = shutil.get_terminal_size() except AttributeError: columns = 80 parser = argparse.ArgumentParser(add_help=False) parser.add_argument( '-l', '--list-devices', action='store_true', help='show list of audio devices and exit') args, remaining = parser.parse_known_args() if args.list_devices: print(sd.query_devices()) parser.exit(0) parser = argparse.ArgumentParser( description=__doc__ + '\n\nSupported keys:' + usage_line, formatter_class=argparse.RawDescriptionHelpFormatter, parents=[parser]) parser.add_argument( '-b', '--block-duration', type=float, metavar='DURATION', default=50, help='block size (default %(default)s milliseconds)') parser.add_argument( '-c', '--columns', type=int, default=columns, help='width of spectrogram') parser.add_argument( '-d', '--device', type=int_or_str, help='input device (numeric ID or substring)') parser.add_argument( '-g', '--gain', type=float, default=10, help='initial gain factor (default %(default)s)') parser.add_argument( '-r', '--range', type=float, nargs=2, metavar=('LOW', 'HIGH'), default=[100, 2000], help='frequency range (default %(default)s Hz)') args = parser.parse_args(remaining) low, high = args.range if high <= low: parser.error('HIGH must be greater than LOW') # Create a nice output gradient using ANSI escape sequences. # Stolen from https://gist.github.com/maurisvh/df919538bcef391bc89f colors = 30, 34, 35, 91, 93, 97 chars = ' :%#\t#%:' gradient = [] for bg, fg in zip(colors, colors[1:]): for char in chars: if char == '\t': bg, fg = fg, bg else: gradient.append(f'\x1b[{fg};{bg + 10}m{char}') try: samplerate = sd.query_devices(args.device, 'input')['default_samplerate'] delta_f = (high - low) / (args.columns - 1) fftsize = math.ceil(samplerate / delta_f) low_bin = math.floor(low / delta_f) def callback(indata, frames, time, status): if status: text = ' ' + str(status) + ' ' print('\x1b[34;40m', text.center(args.columns, '#'), '\x1b[0m', sep='') if any(indata): magnitude = np.abs(np.fft.rfft(indata[:, 0], n=fftsize)) magnitude *= args.gain / fftsize line = (gradient[int(np.clip(x, 0, 1) * (len(gradient) - 1))] for x in magnitude[low_bin:low_bin + args.columns]) print(*line, sep='', end='\x1b[0m\n') else: print('no input') with sd.InputStream(device=args.device, channels=1, callback=callback, blocksize=int(samplerate * args.block_duration / 1000), samplerate=samplerate): while True: response = input() if response in ('', 'q', 'Q'): break for ch in response: if ch == '+': args.gain *= 2 elif ch == '-': args.gain /= 2 else: print('\x1b[31;40m', usage_line.center(args.columns, '#'), '\x1b[0m', sep='') break except KeyboardInterrupt: parser.exit(1, '\nInterrupted by user') except Exception as e: parser.exit(1, type(e).__name__ + ': ' + str(e)) python-sounddevice-0.5.3/examples/wire.py000077500000000000000000000041421507516237500205230ustar00rootroot00000000000000#!/usr/bin/env python3 """Pass input directly to output. https://github.com/PortAudio/portaudio/blob/master/test/patest_wire.c """ import argparse import sounddevice as sd import numpy # Make sure NumPy is loaded before it is used in the callback assert numpy # avoid "imported but unused" message (W0611) def int_or_str(text): """Helper function for argument parsing.""" try: return int(text) except ValueError: return text parser = argparse.ArgumentParser(add_help=False) parser.add_argument( '-l', '--list-devices', action='store_true', help='show list of audio devices and exit') args, remaining = parser.parse_known_args() if args.list_devices: print(sd.query_devices()) parser.exit(0) parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, parents=[parser]) parser.add_argument( '-i', '--input-device', type=int_or_str, help='input device (numeric ID or substring)') parser.add_argument( '-o', '--output-device', type=int_or_str, help='output device (numeric ID or substring)') parser.add_argument( '-c', '--channels', type=int, default=2, help='number of channels') parser.add_argument('--dtype', help='audio data type') parser.add_argument('--samplerate', type=float, help='sampling rate') parser.add_argument('--blocksize', type=int, help='block size') parser.add_argument('--latency', type=float, help='latency in seconds') args = parser.parse_args(remaining) def callback(indata, outdata, frames, time, status): if status: print(status) outdata[:] = indata try: with sd.Stream(device=(args.input_device, args.output_device), samplerate=args.samplerate, blocksize=args.blocksize, dtype=args.dtype, latency=args.latency, channels=args.channels, callback=callback): print('#' * 80) print('press Return to quit') print('#' * 80) input() except KeyboardInterrupt: parser.exit(1, '\nInterrupted by user') except Exception as e: parser.exit(1, type(e).__name__ + ': ' + str(e)) python-sounddevice-0.5.3/make_dist.sh000077500000000000000000000007411507516237500176620ustar00rootroot00000000000000#!/bin/bash set -euo pipefail # Create a source distribution and platform-specific wheel distributions. PYTHON=python3 make_wheel() { PYTHON_SOUNDDEVICE_PLATFORM=$1 PYTHON_SOUNDDEVICE_ARCHITECTURE=${2:-} \ $PYTHON -m build } # This is always 64bit: make_wheel Darwin make_wheel Windows 32bit make_wheel Windows 64bit # This makes sure that the libraries are not copied to the final sdist: rm -rf sounddevice.egg-info/ # This creates a "pure" wheel: make_wheel Linux python-sounddevice-0.5.3/pyproject.toml000066400000000000000000000001311507516237500202700ustar00rootroot00000000000000[build-system] requires = ["setuptools >= 61.0"] build-backend = "setuptools.build_meta" python-sounddevice-0.5.3/setup.py000066400000000000000000000056741507516237500171070ustar00rootroot00000000000000import os import platform from setuptools import setup # "import" __version__ __version__ = 'unknown' for line in open('sounddevice.py'): if line.startswith('__version__'): exec(line) break MACOSX_VERSIONS = '.'.join([ 'macosx_10_6_x86_64', # for compatibility with pip < v21 'macosx_10_6_universal2', ]) # environment variables for cross-platform package creation system = os.environ.get('PYTHON_SOUNDDEVICE_PLATFORM', platform.system()) architecture0 = os.environ.get('PYTHON_SOUNDDEVICE_ARCHITECTURE', platform.architecture()[0]) if system == 'Darwin': libname = 'libportaudio.dylib' elif system == 'Windows': libname = 'libportaudio' + architecture0 + '.dll' libname_asio = 'libportaudio' + architecture0 + '-asio.dll' else: libname = None if libname and os.path.isdir('_sounddevice_data/portaudio-binaries'): packages = ['_sounddevice_data'] package_data = {'_sounddevice_data': ['portaudio-binaries/' + libname, 'portaudio-binaries/README.md']} if system == 'Windows': package_data['_sounddevice_data'].append( 'portaudio-binaries/' + libname_asio) zip_safe = False else: packages = None package_data = None zip_safe = True try: from wheel.bdist_wheel import bdist_wheel except ImportError: cmdclass = {} else: class bdist_wheel_half_pure(bdist_wheel): """Create OS-dependent, but Python-independent wheels.""" def get_tag(self): if system == 'Darwin': oses = MACOSX_VERSIONS elif system == 'Windows': if architecture0 == '32bit': oses = 'win32' else: oses = 'win_amd64' else: oses = 'any' return 'py3', 'none', oses cmdclass = {'bdist_wheel': bdist_wheel_half_pure} setup( name='sounddevice', version=__version__, py_modules=['sounddevice'], packages=packages, package_data=package_data, zip_safe=zip_safe, python_requires='>=3.7', setup_requires=['CFFI>=1.0'], install_requires=['CFFI>=1.0'], extras_require={'NumPy': ['NumPy']}, cffi_modules=['sounddevice_build.py:ffibuilder'], author='Matthias Geier', author_email='Matthias.Geier@gmail.com', description='Play and Record Sound with Python', long_description=open('README.rst').read(), license='MIT', keywords='sound audio PortAudio play record playrec'.split(), url='http://python-sounddevice.readthedocs.io/', project_urls={ 'Source': 'https://github.com/spatialaudio/python-sounddevice', }, platforms='any', classifiers=[ 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Multimedia :: Sound/Audio', ], cmdclass=cmdclass, ) python-sounddevice-0.5.3/sounddevice.py000066400000000000000000003307321507516237500202530ustar00rootroot00000000000000# Copyright (c) 2015-2023 Matthias Geier # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """Play and Record Sound with Python. API overview: * Convenience functions to play and record NumPy arrays: `play()`, `rec()`, `playrec()` and the related functions `wait()`, `stop()`, `get_status()`, `get_stream()` * Functions to get information about the available hardware: `query_devices()`, `query_hostapis()`, `check_input_settings()`, `check_output_settings()` * Module-wide default settings: `default` * Platform-specific settings: `AsioSettings`, `CoreAudioSettings`, `WasapiSettings` * PortAudio streams, using NumPy arrays: `Stream`, `InputStream`, `OutputStream` * PortAudio streams, using Python buffer objects (NumPy not needed): `RawStream`, `RawInputStream`, `RawOutputStream` * Miscellaneous functions and classes: `sleep()`, `get_portaudio_version()`, `CallbackFlags`, `CallbackStop`, `CallbackAbort` Online documentation: https://python-sounddevice.readthedocs.io/ """ __version__ = '0.5.3' import atexit as _atexit import os as _os import platform as _platform import sys as _sys from ctypes.util import find_library as _find_library from _sounddevice import ffi as _ffi try: for _libname in ( 'portaudio', # Default name on POSIX systems 'bin\\libportaudio-2.dll', # DLL from conda-forge 'lib/libportaudio.dylib', # dylib from anaconda ): _libname = _find_library(_libname) if _libname is not None: break else: raise OSError('PortAudio library not found') _lib = _ffi.dlopen(_libname) except OSError: if _platform.system() == 'Darwin': _libname = 'libportaudio.dylib' elif _platform.system() == 'Windows': if 'SD_ENABLE_ASIO' in _os.environ: _libname = 'libportaudio' + _platform.architecture()[0] + '-asio.dll' else: _libname = 'libportaudio' + _platform.architecture()[0] + '.dll' else: raise import _sounddevice_data _libname = _os.path.join( next(iter(_sounddevice_data.__path__)), 'portaudio-binaries', _libname) _lib = _ffi.dlopen(_libname) _sampleformats = { 'float32': _lib.paFloat32, 'int32': _lib.paInt32, 'int24': _lib.paInt24, 'int16': _lib.paInt16, 'int8': _lib.paInt8, 'uint8': _lib.paUInt8, } _initialized = 0 _last_callback = None 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 (to start waiting at a later point, `wait()` can be used). 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 Audio data to be played back. The columns of a two-dimensional array are interpreted as channels, one-dimensional arrays are treated as mono data. The data types *float64*, *float32*, *int32*, *int16*, *int8* and *uint8* can be used. *float64* data is simply converted to *float32* before passing it to PortAudio, because it's not supported natively. mapping : array_like, optional List of channel numbers (starting with 1) where the columns of *data* shall be played back on. Must have the same length as number of channels in *data* (except if *data* is mono, in which case the signal is played back on all given output channels). Each channel number may only appear once in *mapping*. blocking : bool, optional If ``False`` (the default), return immediately (but playback continues in the background), if ``True``, wait until playback is finished. A non-blocking invocation can be stopped with `stop()` or turned into a blocking one with `wait()`. loop : bool, optional Play *data* in a loop. Other Parameters ---------------- samplerate, **kwargs 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 """ ctx = _CallbackContext(loop=loop) ctx.frames = ctx.check_data(data, mapping, kwargs.get('device')) def callback(outdata, frames, time, status): assert len(outdata) == frames ctx.callback_enter(status, outdata) ctx.write_outdata(outdata) ctx.callback_exit() ctx.start_stream(OutputStream, samplerate, ctx.output_channels, ctx.output_dtype, callback, blocking, prime_output_buffers_using_stream_callback=False, **kwargs) 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 (to start waiting at a later point, `wait()` can be used). 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 Number of frames to record. Not needed if *out* is given. channels : int, optional Number of channels to record. Not needed if *mapping* or *out* is given. The default value can be changed with `default.channels`. dtype : str or numpy.dtype, optional Data type of the recording. Not needed if *out* is given. The data types *float64*, *float32*, *int32*, *int16*, *int8* and *uint8* can be used. For ``dtype='float64'``, audio data is recorded in *float32* format and converted afterwards, because it's not natively supported by PortAudio. The default value can be changed with `default.dtype`. mapping : array_like, optional List of channel numbers (starting with 1) to record. If *mapping* is given, *channels* is silently ignored. blocking : bool, optional If ``False`` (the default), return immediately (but recording continues in the background), if ``True``, wait until recording is finished. A non-blocking invocation can be stopped with `stop()` or turned into a blocking one with `wait()`. Returns ------- numpy.ndarray or type(out) The recorded data. .. note:: By default (``blocking=False``), an array of data is returned which is still being written to while recording! The returned data is only valid once recording has stopped. Use `wait()` to make sure the recording is finished. Other Parameters ---------------- out : numpy.ndarray or subclass, optional If *out* is specified, the recorded data is written into the given array instead of creating a new array. In this case, the arguments *frames*, *channels* and *dtype* are silently ignored! If *mapping* is given, its length must match the number of channels in *out*. samplerate, **kwargs 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 """ ctx = _CallbackContext() out, ctx.frames = ctx.check_out(out, frames, channels, dtype, mapping) def callback(indata, frames, time, status): assert len(indata) == frames ctx.callback_enter(status, indata) ctx.read_indata(indata) ctx.callback_exit() ctx.start_stream(InputStream, samplerate, ctx.input_channels, ctx.input_dtype, callback, blocking, **kwargs) return out def playrec(data, samplerate=None, channels=None, dtype=None, out=None, input_mapping=None, output_mapping=None, blocking=False, **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 (to start waiting at a later point, `wait()` can be used). 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 Audio data to be played back. See `play()`. channels : int, sometimes optional Number of input channels, see `rec()`. The number of output channels is obtained from *data.shape*. dtype : str or numpy.dtype, optional Input data type, see `rec()`. If *dtype* is not specified, it is taken from *data.dtype* (i.e. `default.dtype` is ignored). The output data type is obtained from *data.dtype* anyway. input_mapping, output_mapping : array_like, optional See the parameter *mapping* of `rec()` and `play()`, respectively. blocking : bool, optional If ``False`` (the default), return immediately (but continue playback/recording in the background), if ``True``, wait until playback/recording is finished. A non-blocking invocation can be stopped with `stop()` or turned into a blocking one with `wait()`. Returns ------- numpy.ndarray or type(out) The recorded data. See `rec()`. Other Parameters ---------------- out : numpy.ndarray or subclass, optional See `rec()`. samplerate, **kwargs 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 """ ctx = _CallbackContext() output_frames = ctx.check_data(data, output_mapping, kwargs.get('device')) if dtype is None: dtype = ctx.data.dtype # ignore module defaults out, input_frames = ctx.check_out(out, output_frames, channels, dtype, input_mapping) if input_frames != output_frames: raise ValueError('len(data) != len(out)') ctx.frames = input_frames def callback(indata, outdata, frames, time, status): assert len(indata) == len(outdata) == frames ctx.callback_enter(status, indata) ctx.read_indata(indata) ctx.write_outdata(outdata) ctx.callback_exit() ctx.start_stream(Stream, samplerate, (ctx.input_channels, ctx.output_channels), (ctx.input_dtype, ctx.output_dtype), callback, blocking, prime_output_buffers_using_stream_callback=False, **kwargs) return out def wait(ignore_errors=True): """Wait for `play()`/`rec()`/`playrec()` to be finished. Playback/recording can be stopped with a `KeyboardInterrupt`. Returns ------- CallbackFlags or None If at least one buffer over-/underrun happened during the last playback/recording, a `CallbackFlags` object is returned. See Also -------- get_status """ if _last_callback: return _last_callback.wait(ignore_errors) def stop(ignore_errors=True): """Stop playback/recording. This only stops `play()`, `rec()` and `playrec()`, but has no influence on streams created with `Stream`, `InputStream`, `OutputStream`, `RawStream`, `RawInputStream`, `RawOutputStream`. """ if _last_callback: # Calling stop() before close() is necessary for older PortAudio # versions, see issue #87: _last_callback.stream.stop(ignore_errors) _last_callback.stream.close(ignore_errors) def get_status(): """Get info about over-/underflows in `play()`/`rec()`/`playrec()`. Returns ------- CallbackFlags A `CallbackFlags` object that holds information about the last invocation of `play()`, `rec()` or `playrec()`. See Also -------- wait """ if _last_callback: return _last_callback.status else: raise RuntimeError('play()/rec()/playrec() was not called yet') def get_stream(): """Get a reference to the current stream. This applies only to streams created by calls to `play()`, `rec()` or `playrec()`. Returns ------- Stream An `OutputStream`, `InputStream` or `Stream` associated with the last invocation of `play()`, `rec()` or `playrec()`, respectively. """ if _last_callback: return _last_callback.stream else: raise RuntimeError('play()/rec()/playrec() was not called yet') def query_devices(device=None, kind=None): """Return information about available devices. Information and capabilities of PortAudio devices. Devices may support input, output or both input and output. To find the default input/output device(s), use `default.device`. Parameters ---------- device : int or str, optional Numeric device ID or device name substring(s). If specified, information about only the given *device* is returned in a single dictionary. kind : {'input', 'output'}, optional If *device* is not specified and *kind* is ``'input'`` or ``'output'``, a single dictionary is returned with information about the default input or output device, respectively. Returns ------- dict or DeviceList A dictionary with information about the given *device* or -- if no arguments were specified -- a `DeviceList` containing one dictionary for each available device. The dictionaries have the following keys: ``'name'`` The name of the device. ``'index'`` The device index. ``'hostapi'`` The ID of the corresponding host API. Use `query_hostapis()` to get information about a host API. ``'max_input_channels'``, ``'max_output_channels'`` The maximum number of input/output channels supported by the device. See `default.channels`. ``'default_low_input_latency'``, ``'default_low_output_latency'`` Default latency values for interactive performance. This is used if `default.latency` (or the *latency* argument of `playrec()`, `Stream` etc.) is set to ``'low'``. ``'default_high_input_latency'``, ``'default_high_output_latency'`` Default latency values for robust non-interactive applications (e.g. playing sound files). This is used if `default.latency` (or the *latency* argument of `playrec()`, `Stream` etc.) is set to ``'high'``. ``'default_samplerate'`` The default sampling frequency of the device. This is used if `default.samplerate` is not set. Notes ----- The list of devices can also be displayed in a terminal: .. code-block:: sh python3 -m sounddevice Examples -------- The returned `DeviceList` can be indexed and iterated over like any sequence type (yielding the abovementioned dictionaries), but it also has a special string representation which is shown when used in an interactive Python session. Each available device is listed on one line together with the corresponding device ID, which can be assigned to `default.device` or used as *device* argument in `play()`, `Stream` etc. The first character of a line is ``>`` for the default input device, ``<`` for the default output device and ``*`` for the default input/output device. After the device ID and the device name, the corresponding host API name is displayed. In the end of each line, the maximum number of input and output channels is shown. On a GNU/Linux computer it might look somewhat like this: >>> import sounddevice as sd >>> sd.query_devices() 0 HDA Intel: ALC662 rev1 Analog (hw:0,0), ALSA (2 in, 2 out) 1 HDA Intel: ALC662 rev1 Digital (hw:0,1), ALSA (0 in, 2 out) 2 HDA Intel: HDMI 0 (hw:0,3), ALSA (0 in, 8 out) 3 sysdefault, ALSA (128 in, 128 out) 4 front, ALSA (0 in, 2 out) 5 surround40, ALSA (0 in, 2 out) 6 surround51, ALSA (0 in, 2 out) 7 surround71, ALSA (0 in, 2 out) 8 iec958, ALSA (0 in, 2 out) 9 spdif, ALSA (0 in, 2 out) 10 hdmi, ALSA (0 in, 8 out) * 11 default, ALSA (128 in, 128 out) 12 dmix, ALSA (0 in, 2 out) 13 /dev/dsp, OSS (16 in, 16 out) Note that ALSA provides access to some "real" and some "virtual" devices. The latter sometimes have a ridiculously high number of (virtual) inputs and outputs. On macOS, you might get something similar to this: >>> sd.query_devices() 0 Built-in Line Input, Core Audio (2 in, 0 out) > 1 Built-in Digital Input, Core Audio (2 in, 0 out) < 2 Built-in Output, Core Audio (0 in, 2 out) 3 Built-in Line Output, Core Audio (0 in, 2 out) 4 Built-in Digital Output, Core Audio (0 in, 2 out) """ if kind not in ('input', 'output', None): raise ValueError(f'Invalid kind: {kind!r}') if device is None and kind is None: return DeviceList(query_devices(i) for i in range(_check(_lib.Pa_GetDeviceCount()))) device = _get_device_id(device, kind, raise_on_error=True) info = _lib.Pa_GetDeviceInfo(device) if not info: raise PortAudioError(f'Error querying device {device}') assert info.structVersion == 2 name_bytes = _ffi.string(info.name) try: # We don't know beforehand if DirectSound and MME device names use # 'utf-8' or 'mbcs' encoding. Let's try 'utf-8' first, because it more # likely raises an exception on 'mbcs' data than vice versa, see also # https://github.com/spatialaudio/python-sounddevice/issues/72. name = name_bytes.decode('utf-8') except UnicodeDecodeError: api_idx = _lib.Pa_HostApiTypeIdToHostApiIndex if info.hostApi in (api_idx(_lib.paDirectSound), api_idx(_lib.paMME)): name = name_bytes.decode('mbcs') elif info.hostApi == api_idx(_lib.paASIO): # See https://github.com/spatialaudio/python-sounddevice/issues/490 import locale name = name_bytes.decode(locale.getpreferredencoding()) else: raise device_dict = { 'name': name, 'index': device, 'hostapi': info.hostApi, 'max_input_channels': info.maxInputChannels, 'max_output_channels': info.maxOutputChannels, 'default_low_input_latency': info.defaultLowInputLatency, 'default_low_output_latency': info.defaultLowOutputLatency, 'default_high_input_latency': info.defaultHighInputLatency, 'default_high_output_latency': info.defaultHighOutputLatency, 'default_samplerate': info.defaultSampleRate, } if kind and device_dict['max_' + kind + '_channels'] < 1: raise ValueError( 'Not an {} device: {!r}'.format(kind, device_dict['name'])) return device_dict def query_hostapis(index=None): """Return information about available host APIs. Parameters ---------- index : int, optional If specified, information about only the given host API *index* is returned in a single dictionary. Returns ------- dict or tuple of dict A dictionary with information about the given host API *index* or -- if no *index* was specified -- a tuple containing one dictionary for each available host API. The dictionaries have the following keys: ``'name'`` The name of the host API. ``'devices'`` A list of device IDs belonging to the host API. Use `query_devices()` to get information about a device. ``'default_input_device'``, ``'default_output_device'`` The device ID of the default input/output device of the host API. If no default input/output device exists for the given host API, this is -1. .. note:: The overall default device(s) -- which can be overwritten by assigning to `default.device` -- take(s) precedence over `default.hostapi` and the information in the abovementioned dictionaries. See Also -------- query_devices """ if index is None: return tuple(query_hostapis(i) for i in range(_check(_lib.Pa_GetHostApiCount()))) info = _lib.Pa_GetHostApiInfo(index) if not info: raise PortAudioError(f'Error querying host API {index}') assert info.structVersion == 1 return { 'name': _ffi.string(info.name).decode(), 'devices': [_lib.Pa_HostApiDeviceIndexToDeviceIndex(index, i) for i in range(info.deviceCount)], 'default_input_device': info.defaultInputDevice, 'default_output_device': info.defaultOutputDevice, } def check_input_settings(device=None, channels=None, dtype=None, extra_settings=None, samplerate=None): """Check if given input device settings are supported. All parameters are optional, `default` settings are used for any unspecified parameters. If the settings are supported, the function does nothing; if not, an exception is raised. Parameters ---------- device : int or str, optional Device ID or device name substring(s), see `default.device`. channels : int, optional Number of input channels, see `default.channels`. dtype : str or numpy.dtype, optional Data type for input samples, see `default.dtype`. extra_settings : settings object, optional This can be used for host-API-specific input settings. See `default.extra_settings`. samplerate : float, optional Sampling frequency, see `default.samplerate`. """ parameters, dtype, samplesize, samplerate = _get_stream_parameters( 'input', device=device, channels=channels, dtype=dtype, latency=None, extra_settings=extra_settings, samplerate=samplerate) _check(_lib.Pa_IsFormatSupported(parameters, _ffi.NULL, samplerate)) def check_output_settings(device=None, channels=None, dtype=None, extra_settings=None, samplerate=None): """Check if given output device settings are supported. Same as `check_input_settings()`, just for output device settings. """ parameters, dtype, samplesize, samplerate = _get_stream_parameters( 'output', device=device, channels=channels, dtype=dtype, latency=None, extra_settings=extra_settings, samplerate=samplerate) _check(_lib.Pa_IsFormatSupported(_ffi.NULL, parameters, samplerate)) def sleep(msec): """Put the caller to sleep for at least *msec* milliseconds. The function may sleep longer than requested so don't rely on this for accurate musical timing. """ _lib.Pa_Sleep(msec) def get_portaudio_version(): """Get version information for the PortAudio library. Returns the release number and a textual description of the current PortAudio build, e.g. :: (1899, 'PortAudio V19-devel (built Feb 15 2014 23:28:00)') """ return _lib.Pa_GetVersion(), _ffi.string(_lib.Pa_GetVersionText()).decode() class _StreamBase: """Direct or indirect base class for all stream classes.""" def __init__(self, kind, samplerate=None, blocksize=None, device=None, channels=None, dtype=None, latency=None, extra_settings=None, callback=None, finished_callback=None, clip_off=None, dither_off=None, never_drop_input=None, prime_output_buffers_using_stream_callback=None, userdata=None, wrap_callback=None): """Base class for PortAudio streams. This class should only be used by library authors who want to create their own custom stream classes. Most users should use the derived classes `Stream`, `InputStream`, `OutputStream`, `RawStream`, `RawInputStream` and `RawOutputStream` instead. This class has the same properties and methods as `Stream`, except for `~Stream.read_available`/`~Stream.read()` and `~Stream.write_available`/`~Stream.write()`. It can be created with the same parameters as `Stream`, except that there are three additional parameters and the *callback* parameter also accepts a C function pointer. Parameters ---------- kind : {'input', 'output', 'duplex'} The desired type of stream: for recording, playback or both. callback : Python callable or CData function pointer, optional If *wrap_callback* is ``None`` this can be a function pointer provided by CFFI. Otherwise, it has to be a Python callable. wrap_callback : {'array', 'buffer'}, optional If *callback* is a Python callable, this selects whether the audio data is provided as NumPy array (like in `Stream`) or as Python buffer object (like in `RawStream`). userdata : CData void pointer This is passed to the underlying C callback function on each call and can only be accessed from a *callback* provided as ``CData`` function pointer. Examples -------- A usage example of this class can be seen at https://github.com/spatialaudio/python-rtmixer. """ assert kind in ('input', 'output', 'duplex') assert wrap_callback in ('array', 'buffer', None) if wrap_callback == 'array': # Import NumPy as early as possible, see: # https://github.com/spatialaudio/python-sounddevice/issues/487 import numpy assert numpy # avoid "imported but unused" message (W0611) if blocksize is None: blocksize = default.blocksize if clip_off is None: clip_off = default.clip_off if dither_off is None: dither_off = default.dither_off if never_drop_input is None: never_drop_input = default.never_drop_input if prime_output_buffers_using_stream_callback is None: prime_output_buffers_using_stream_callback = \ default.prime_output_buffers_using_stream_callback stream_flags = _lib.paNoFlag if clip_off: stream_flags |= _lib.paClipOff if dither_off: stream_flags |= _lib.paDitherOff if never_drop_input: stream_flags |= _lib.paNeverDropInput if prime_output_buffers_using_stream_callback: stream_flags |= _lib.paPrimeOutputBuffersUsingStreamCallback if kind == 'duplex': idevice, odevice = _split(device) ichannels, ochannels = _split(channels) idtype, odtype = _split(dtype) ilatency, olatency = _split(latency) iextra, oextra = _split(extra_settings) iparameters, idtype, isize, isamplerate = _get_stream_parameters( 'input', idevice, ichannels, idtype, ilatency, iextra, samplerate) oparameters, odtype, osize, osamplerate = _get_stream_parameters( 'output', odevice, ochannels, odtype, olatency, oextra, samplerate) self._dtype = idtype, odtype self._device = iparameters.device, oparameters.device self._channels = iparameters.channelCount, oparameters.channelCount self._samplesize = isize, osize if isamplerate != osamplerate: raise ValueError( 'Input and output device must have the same samplerate') else: samplerate = isamplerate else: parameters, self._dtype, self._samplesize, samplerate = \ _get_stream_parameters(kind, device, channels, dtype, latency, extra_settings, samplerate) self._device = parameters.device self._channels = parameters.channelCount iparameters = _ffi.NULL oparameters = _ffi.NULL if kind == 'input': iparameters = parameters elif kind == 'output': oparameters = parameters ffi_callback = _ffi.callback('PaStreamCallback', error=_lib.paAbort) if callback is None: callback_ptr = _ffi.NULL elif kind == 'input' and wrap_callback == 'buffer': @ffi_callback def callback_ptr(iptr, optr, frames, time, status, _): data = _buffer(iptr, frames, self._channels, self._samplesize) return _wrap_callback(callback, data, frames, time, status) elif kind == 'input' and wrap_callback == 'array': @ffi_callback def callback_ptr(iptr, optr, frames, time, status, _): data = _array( _buffer(iptr, frames, self._channels, self._samplesize), self._channels, self._dtype) return _wrap_callback(callback, data, frames, time, status) elif kind == 'output' and wrap_callback == 'buffer': @ffi_callback def callback_ptr(iptr, optr, frames, time, status, _): data = _buffer(optr, frames, self._channels, self._samplesize) return _wrap_callback(callback, data, frames, time, status) elif kind == 'output' and wrap_callback == 'array': @ffi_callback def callback_ptr(iptr, optr, frames, time, status, _): data = _array( _buffer(optr, frames, self._channels, self._samplesize), self._channels, self._dtype) return _wrap_callback(callback, data, frames, time, status) elif kind == 'duplex' and wrap_callback == 'buffer': @ffi_callback def callback_ptr(iptr, optr, frames, time, status, _): ichannels, ochannels = self._channels isize, osize = self._samplesize idata = _buffer(iptr, frames, ichannels, isize) odata = _buffer(optr, frames, ochannels, osize) return _wrap_callback( callback, idata, odata, frames, time, status) elif kind == 'duplex' and wrap_callback == 'array': @ffi_callback def callback_ptr(iptr, optr, frames, time, status, _): ichannels, ochannels = self._channels idtype, odtype = self._dtype isize, osize = self._samplesize idata = _array(_buffer(iptr, frames, ichannels, isize), ichannels, idtype) odata = _array(_buffer(optr, frames, ochannels, osize), ochannels, odtype) return _wrap_callback( callback, idata, odata, frames, time, status) else: # Use cast() to allow CData from different FFI instance: callback_ptr = _ffi.cast('PaStreamCallback*', callback) # CFFI callback object must be kept alive during stream lifetime: self._callback = callback_ptr if userdata is None: userdata = _ffi.NULL self._ptr = _ffi.new('PaStream**') _check(_lib.Pa_OpenStream(self._ptr, iparameters, oparameters, samplerate, blocksize, stream_flags, callback_ptr, userdata), f'Error opening {self.__class__.__name__}') # dereference PaStream** --> PaStream* self._ptr = self._ptr[0] self._blocksize = blocksize info = _lib.Pa_GetStreamInfo(self._ptr) if not info: raise PortAudioError('Could not obtain stream info') # TODO: assert info.structVersion == 1 self._samplerate = info.sampleRate if not oparameters: self._latency = info.inputLatency elif not iparameters: self._latency = info.outputLatency else: self._latency = info.inputLatency, info.outputLatency if finished_callback: if isinstance(finished_callback, _ffi.CData): self._finished_callback = finished_callback else: def finished_callback_wrapper(_): return finished_callback() # CFFI callback object is kept alive during stream lifetime: self._finished_callback = _ffi.callback( 'PaStreamFinishedCallback', finished_callback_wrapper) _check(_lib.Pa_SetStreamFinishedCallback(self._ptr, self._finished_callback)) # Avoid confusion if something goes wrong before assigning self._ptr: _ptr = _ffi.NULL @property def samplerate(self): """The sampling frequency in Hertz (= frames per second). In cases where the hardware sampling frequency is inaccurate and PortAudio is aware of it, the value of this field may be different from the *samplerate* parameter passed to `Stream()`. If information about the actual hardware sampling frequency is not available, this field will have the same value as the *samplerate* parameter passed to `Stream()`. """ return self._samplerate @property def blocksize(self): """Number of frames per block. The special value 0 means that the blocksize can change between blocks. See the *blocksize* argument of `Stream`. """ return self._blocksize @property def device(self): """IDs of the input/output device.""" return self._device @property def channels(self): """The number of input/output channels.""" return self._channels @property def dtype(self): """Data type of the audio samples. See Also -------- default.dtype, samplesize """ return self._dtype @property def samplesize(self): """The size in bytes of a single sample. See Also -------- dtype """ return self._samplesize @property def latency(self): """The input/output latency of the stream in seconds. This value provides the most accurate estimate of input/output latency available to the implementation. It may differ significantly from the *latency* value(s) passed to `Stream()`. """ return self._latency @property def active(self): """``True`` when the stream is active, ``False`` otherwise. A stream is active after a successful call to `start()`, until it becomes inactive either as a result of a call to `stop()` or `abort()`, or as a result of an exception raised in the stream callback. In the latter case, the stream is considered inactive after the last buffer has finished playing. See Also -------- stopped """ if self.closed: return False return _check(_lib.Pa_IsStreamActive(self._ptr)) == 1 @property def stopped(self): """``True`` when the stream is stopped, ``False`` otherwise. A stream is considered to be stopped prior to a successful call to `start()` and after a successful call to `stop()` or `abort()`. If a stream callback is cancelled (by raising an exception) the stream is *not* considered to be stopped. See Also -------- active """ if self.closed: return True return _check(_lib.Pa_IsStreamStopped(self._ptr)) == 1 @property def closed(self): """``True`` after a call to `close()`, ``False`` otherwise.""" return self._ptr == _ffi.NULL @property def time(self): """The current stream time in seconds. This is according to the same clock used to generate the timestamps passed with the *time* argument to the stream callback (see the *callback* argument of `Stream`). The time values are monotonically increasing and have unspecified origin. This provides valid time values for the entire life of the stream, from when the stream is opened until it is closed. Starting and stopping the stream does not affect the passage of time as provided here. This time may be used for synchronizing other events to the audio stream, for example synchronizing audio to MIDI. """ time = _lib.Pa_GetStreamTime(self._ptr) if not time: raise PortAudioError('Error getting stream time') return time @property def cpu_load(self): """CPU usage information for the stream. The "CPU Load" is a fraction of total CPU time consumed by a callback stream's audio processing routines including, but not limited to the client supplied stream callback. This function does not work with blocking read/write streams. This may be used in the stream callback function or in the application. It provides a floating point value, typically between 0.0 and 1.0, where 1.0 indicates that the stream callback is consuming the maximum number of CPU cycles possible to maintain real-time operation. A value of 0.5 would imply that PortAudio and the stream callback was consuming roughly 50% of the available CPU time. The value may exceed 1.0. A value of 0.0 will always be returned for a blocking read/write stream, or if an error occurs. """ return _lib.Pa_GetStreamCpuLoad(self._ptr) def __enter__(self): """Start the stream in the beginning of a "with" statement.""" self.start() return self def __exit__(self, *args): """Stop and close the stream when exiting a "with" statement.""" self.stop() self.close() def start(self): """Commence audio processing. See Also -------- stop, abort """ err = _lib.Pa_StartStream(self._ptr) if err != _lib.paStreamIsNotStopped: _check(err, 'Error starting stream') def stop(self, ignore_errors=True): """Terminate audio processing. This waits until all pending audio buffers have been played before it returns. See Also -------- start, abort """ err = _lib.Pa_StopStream(self._ptr) if not ignore_errors: _check(err, 'Error stopping stream') def abort(self, ignore_errors=True): """Terminate audio processing immediately. This does not wait for pending buffers to complete. See Also -------- start, stop """ err = _lib.Pa_AbortStream(self._ptr) if not ignore_errors: _check(err, 'Error aborting stream') def close(self, ignore_errors=True): """Close the stream. If the audio stream is active any pending buffers are discarded as if `abort()` had been called. """ err = _lib.Pa_CloseStream(self._ptr) self._ptr = _ffi.NULL if not ignore_errors: _check(err, 'Error closing stream') class _InputStreamBase(_StreamBase): """Base class for input stream classes.""" @property def read_available(self): """The number of frames that can be read without waiting. Returns a value representing the maximum number of frames that can be read from the stream without blocking or busy waiting. """ return _check(_lib.Pa_GetStreamReadAvailable(self._ptr)) def _raw_read(self, frames): """Read samples from the stream into a buffer. This is the same as `Stream.read()`, except that it returns a plain Python buffer object instead of a NumPy array. NumPy is not necessary for using this. Parameters ---------- frames : int The number of frames to be read. See `Stream.read()`. Returns ------- data : buffer A buffer of interleaved samples. The buffer contains samples in the format specified by the *dtype* parameter used to open the stream, and the number of channels specified by *channels*. See also `~Stream.samplesize`. overflowed : bool See `Stream.read()`. """ channels, _ = _split(self._channels) samplesize, _ = _split(self._samplesize) data = _ffi.new('signed char[]', channels * samplesize * frames) err = _lib.Pa_ReadStream(self._ptr, data, frames) if err == _lib.paInputOverflowed: overflowed = True else: _check(err) overflowed = False return _ffi.buffer(data), overflowed class RawInputStream(_InputStreamBase): """Raw stream for recording only. See __init__() and RawStream.""" def __init__(self, samplerate=None, blocksize=None, device=None, channels=None, dtype=None, latency=None, extra_settings=None, callback=None, finished_callback=None, clip_off=None, dither_off=None, never_drop_input=None, prime_output_buffers_using_stream_callback=None): """PortAudio input stream (using buffer objects). This is the same as `InputStream`, except that the *callback* function and `~RawStream.read()` work on plain Python buffer objects instead of on NumPy arrays. NumPy is not necessary for using this. Parameters ---------- dtype : str See `RawStream`. callback : callable User-supplied function to consume audio data in response to requests from an active stream. The callback must have this signature: .. code-block:: text callback(indata: buffer, frames: int, time: CData, status: CallbackFlags) -> None The arguments are the same as in the *callback* parameter of `RawStream`, except that *outdata* is missing. See Also -------- RawStream, Stream """ _StreamBase.__init__(self, kind='input', wrap_callback='buffer', **_remove_self(locals())) read = _InputStreamBase._raw_read class _OutputStreamBase(_StreamBase): """Base class for output stream classes.""" @property def write_available(self): """The number of frames that can be written without waiting. Returns a value representing the maximum number of frames that can be written to the stream without blocking or busy waiting. """ return _check(_lib.Pa_GetStreamWriteAvailable(self._ptr)) def _raw_write(self, data): """Write samples to the stream. This is the same as `Stream.write()`, except that it expects a plain Python buffer object instead of a NumPy array. NumPy is not necessary for using this. Parameters ---------- data : buffer or bytes or iterable of int A buffer of interleaved samples. The buffer contains samples in the format specified by the *dtype* argument used to open the stream, and the number of channels specified by *channels*. The length of the buffer is not constrained to a specific range, however high performance applications will want to match this parameter to the *blocksize* parameter used when opening the stream. See also `~Stream.samplesize`. Returns ------- underflowed : bool See `Stream.write()`. """ try: data = _ffi.from_buffer(data) except AttributeError: pass # from_buffer() not supported except TypeError: pass # input is not a buffer _, samplesize = _split(self._samplesize) _, channels = _split(self._channels) samples, remainder = divmod(len(data), samplesize) if remainder: raise ValueError('len(data) not divisible by samplesize') frames, remainder = divmod(samples, channels) if remainder: raise ValueError('Number of samples not divisible by channels') err = _lib.Pa_WriteStream(self._ptr, data, frames) if err == _lib.paOutputUnderflowed: underflowed = True else: _check(err) underflowed = False return underflowed class RawOutputStream(_OutputStreamBase): """Raw stream for playback only. See __init__() and RawStream.""" def __init__(self, samplerate=None, blocksize=None, device=None, channels=None, dtype=None, latency=None, extra_settings=None, callback=None, finished_callback=None, clip_off=None, dither_off=None, never_drop_input=None, prime_output_buffers_using_stream_callback=None): """PortAudio output stream (using buffer objects). This is the same as `OutputStream`, except that the *callback* function and `~RawStream.write()` work on plain Python buffer objects instead of on NumPy arrays. NumPy is not necessary for using this. Parameters ---------- dtype : str See `RawStream`. callback : callable User-supplied function to generate audio data in response to requests from an active stream. The callback must have this signature: .. code-block:: text callback(outdata: buffer, frames: int, time: CData, status: CallbackFlags) -> None The arguments are the same as in the *callback* parameter of `RawStream`, except that *indata* is missing. See Also -------- RawStream, Stream """ _StreamBase.__init__(self, kind='output', wrap_callback='buffer', **_remove_self(locals())) write = _OutputStreamBase._raw_write class RawStream(RawInputStream, RawOutputStream): """Raw stream for playback and recording. See __init__().""" def __init__(self, samplerate=None, blocksize=None, device=None, channels=None, dtype=None, latency=None, extra_settings=None, callback=None, finished_callback=None, clip_off=None, dither_off=None, never_drop_input=None, prime_output_buffers_using_stream_callback=None): """PortAudio input/output stream (using buffer objects). This is the same as `Stream`, except that the *callback* function and `read()`/`write()` work on plain Python buffer objects instead of on NumPy arrays. NumPy is not necessary for using this. To open a "raw" input-only or output-only stream use `RawInputStream` or `RawOutputStream`, respectively. If you want to handle audio data as NumPy arrays instead of buffer objects, use `Stream`, `InputStream` or `OutputStream`. Parameters ---------- dtype : str or pair of str The sample format of the buffers provided to the stream callback, `read()` or `write()`. In addition to the formats supported by `Stream` (``'float32'``, ``'int32'``, ``'int16'``, ``'int8'``, ``'uint8'``), this also supports ``'int24'``, i.e. packed 24 bit format. The default value can be changed with `default.dtype`. See also `~Stream.samplesize`. callback : callable User-supplied function to consume, process or generate audio data in response to requests from an active stream. The callback must have this signature: .. code-block:: text callback(indata: buffer, outdata: buffer, frames: int, time: CData, status: CallbackFlags) -> None The arguments are the same as in the *callback* parameter of `Stream`, except that *indata* and *outdata* are plain Python buffer objects instead of NumPy arrays. See Also -------- RawInputStream, RawOutputStream, Stream """ _StreamBase.__init__(self, kind='duplex', wrap_callback='buffer', **_remove_self(locals())) class InputStream(_InputStreamBase): """Stream for input only. See __init__() and Stream.""" def __init__(self, samplerate=None, blocksize=None, device=None, channels=None, dtype=None, latency=None, extra_settings=None, callback=None, finished_callback=None, clip_off=None, dither_off=None, never_drop_input=None, prime_output_buffers_using_stream_callback=None): """PortAudio input stream (using NumPy). This has the same methods and attributes as `Stream`, except `~Stream.write()` and `~Stream.write_available`. Furthermore, the stream callback is expected to have a different signature (see below). Parameters ---------- callback : callable User-supplied function to consume audio in response to requests from an active stream. The callback must have this signature: .. code-block:: text callback(indata: numpy.ndarray, frames: int, time: CData, status: CallbackFlags) -> None The arguments are the same as in the *callback* parameter of `Stream`, except that *outdata* is missing. See Also -------- Stream, RawInputStream """ _StreamBase.__init__(self, kind='input', wrap_callback='array', **_remove_self(locals())) def read(self, frames): """Read samples from the stream into a NumPy array. The function doesn't return until all requested *frames* have been read -- this may involve waiting for the operating system to supply the data (except if no more than `read_available` frames were requested). This is the same as `RawStream.read()`, except that it returns a NumPy array instead of a plain Python buffer object. Parameters ---------- frames : int The number of frames to be read. This parameter is not constrained to a specific range, however high performance applications will want to match this parameter to the *blocksize* parameter used when opening the stream. Returns ------- data : numpy.ndarray A two-dimensional `numpy.ndarray` with one column per channel (i.e. with a shape of ``(frames, channels)``) and with a data type specified by `dtype`. overflowed : bool ``True`` if input data was discarded by PortAudio after the previous call and before this call. """ dtype, _ = _split(self._dtype) channels, _ = _split(self._channels) data, overflowed = _InputStreamBase._raw_read(self, frames) data = _array(data, channels, dtype) return data, overflowed class OutputStream(_OutputStreamBase): """Stream for output only. See __init__() and Stream.""" def __init__(self, samplerate=None, blocksize=None, device=None, channels=None, dtype=None, latency=None, extra_settings=None, callback=None, finished_callback=None, clip_off=None, dither_off=None, never_drop_input=None, prime_output_buffers_using_stream_callback=None): """PortAudio output stream (using NumPy). This has the same methods and attributes as `Stream`, except `~Stream.read()` and `~Stream.read_available`. Furthermore, the stream callback is expected to have a different signature (see below). Parameters ---------- callback : callable User-supplied function to generate audio data in response to requests from an active stream. The callback must have this signature: .. code-block:: text callback(outdata: numpy.ndarray, frames: int, time: CData, status: CallbackFlags) -> None The arguments are the same as in the *callback* parameter of `Stream`, except that *indata* is missing. See Also -------- Stream, RawOutputStream """ _StreamBase.__init__(self, kind='output', wrap_callback='array', **_remove_self(locals())) def write(self, data): """Write samples to the stream. This function doesn't return until the entire buffer has been consumed -- this may involve waiting for the operating system to consume the data (except if *data* contains no more than `write_available` frames). This is the same as `RawStream.write()`, except that it expects a NumPy array instead of a plain Python buffer object. Parameters ---------- data : array_like A two-dimensional array-like object with one column per channel (i.e. with a shape of ``(frames, channels)``) and with a data type specified by `dtype`. A one-dimensional array can be used for mono data. The array layout must be C-contiguous (see :func:`numpy.ascontiguousarray`). The length of the buffer is not constrained to a specific range, however high performance applications will want to match this parameter to the *blocksize* parameter used when opening the stream. Returns ------- underflowed : bool ``True`` if additional output data was inserted after the previous call and before this call. """ import numpy as np data = np.asarray(data) _, dtype = _split(self._dtype) _, channels = _split(self._channels) if data.ndim < 2: data = data.reshape(-1, 1) elif data.ndim > 2: raise ValueError('data must be one- or two-dimensional') if data.shape[1] != channels: raise ValueError('number of channels must match') if data.dtype != dtype: raise TypeError('dtype mismatch: {!r} vs {!r}'.format( data.dtype.name, dtype)) if not data.flags.c_contiguous: raise TypeError('data must be C-contiguous') return _OutputStreamBase._raw_write(self, data) class Stream(InputStream, OutputStream): """Stream for input and output. See __init__().""" def __init__(self, samplerate=None, blocksize=None, device=None, channels=None, dtype=None, latency=None, extra_settings=None, callback=None, finished_callback=None, clip_off=None, dither_off=None, never_drop_input=None, prime_output_buffers_using_stream_callback=None): """PortAudio stream for simultaneous input and output (using NumPy). To open an input-only or output-only stream use `InputStream` or `OutputStream`, respectively. If you want to handle audio data as plain buffer objects instead of NumPy arrays, use `RawStream`, `RawInputStream` or `RawOutputStream`. A single stream can provide multiple channels of real-time streaming audio input and output to a client application. A stream provides access to audio hardware represented by one or more devices. Depending on the underlying host API, it may be possible to open multiple streams using the same device, however this behavior is implementation defined. Portable applications should assume that a device may be simultaneously used by at most one stream. The arguments *device*, *channels*, *dtype* and *latency* can be either single values (which will be used for both input and output parameters) or pairs of values (where the first one is the value for the input and the second one for the output). All arguments are optional, the values for unspecified parameters are taken from the `default` object. If one of the values of a parameter pair is ``None``, the corresponding value from `default` will be used instead. The created stream is inactive (see `active`, `stopped`). It can be started with `start()`. Every stream object is also a :ref:`context manager `, i.e. it can be used in a :ref:`with statement ` to automatically call `start()` in the beginning of the statement and `stop()` and `close()` on exit. Parameters ---------- samplerate : float, optional The desired sampling frequency (for both input and output). The default value can be changed with `default.samplerate`. blocksize : int, optional The number of frames passed to the stream callback function, or the preferred block granularity for a blocking read/write stream. The special value ``blocksize=0`` (which is the default) may be used to request that the stream callback will receive an optimal (and possibly varying) number of frames based on host requirements and the requested latency settings. The default value can be changed with `default.blocksize`. .. note:: With some host APIs, the use of non-zero *blocksize* for a callback stream may introduce an additional layer of buffering which could introduce additional latency. PortAudio guarantees that the additional latency will be kept to the theoretical minimum however, it is strongly recommended that a non-zero *blocksize* value only be used when your algorithm requires a fixed number of frames per stream callback. device : int or str or pair thereof, optional Device index(es) or query string(s) specifying the device(s) to be used. The default value(s) can be changed with `default.device`. If a string is given, the device is selected which contains all space-separated parts in the right order. Each device string contains the name of the corresponding host API in the end. The string comparison is case-insensitive. channels : int or pair of int, optional The number of channels of sound to be delivered to the stream callback or accessed by `read()` or `write()`. It can range from 1 to the value of ``'max_input_channels'`` or ``'max_output_channels'`` in the dict returned by `query_devices()`. By default, the maximum possible number of channels for the selected device is used (which may not be what you want; see `query_devices()`). The default value(s) can be changed with `default.channels`. dtype : str or numpy.dtype or pair thereof, optional The sample format of the `numpy.ndarray` provided to the stream callback, `read()` or `write()`. It may be any of *float32*, *int32*, *int16*, *int8*, *uint8*. See `numpy.dtype`. The *float64* data type is not supported, this is only supported for convenience in `play()`/`rec()`/`playrec()`. The packed 24 bit format ``'int24'`` is only supported in the "raw" stream classes, see `RawStream`. The default value(s) can be changed with `default.dtype`. If NumPy is available, the corresponding `numpy.dtype` objects can be used as well. The floating point representations ``'float32'`` and ``'float64'`` use ``+1.0`` and ``-1.0`` as the maximum and minimum values, respectively. ``'uint8'`` is an unsigned 8 bit format where ``128`` is considered "ground". latency : float or {'low', 'high'} or pair thereof, optional The desired latency in seconds. The special values ``'low'`` and ``'high'`` (latter being the default) select the device's default low and high latency, respectively (see `query_devices()`). ``'high'`` is typically more robust (i.e. buffer under-/overflows are less likely), but the latency may be too large for interactive applications. .. note:: Specifying the desired latency as ``'high'`` does not *guarantee* a stable audio stream. For reference, by default Audacity_ specifies a desired latency of ``0.1`` seconds and typically achieves robust performance. .. _Audacity: https://www.audacityteam.org/ The default value(s) can be changed with `default.latency`. Actual latency values for an open stream can be retrieved using the `latency` attribute. extra_settings : settings object or pair thereof, optional This can be used for host-API-specific input/output settings. See `default.extra_settings`. callback : callable, optional User-supplied function to consume, process or generate audio data in response to requests from an `active` stream. When a stream is running, PortAudio calls the stream callback periodically. The callback function is responsible for processing and filling input and output buffers, respectively. If no *callback* is given, the stream will be opened in "blocking read/write" mode. In blocking mode, the client can receive sample data using `read()` and write sample data using `write()`, the number of frames that may be read or written without blocking is returned by `read_available` and `write_available`, respectively. The callback must have this signature: .. code-block:: text callback(indata: ndarray, outdata: ndarray, frames: int, time: CData, status: CallbackFlags) -> None The first and second argument are the input and output buffer, respectively, as two-dimensional `numpy.ndarray` with one column per channel (i.e. with a shape of ``(frames, channels)``) and with a data type specified by `dtype`. The output buffer contains uninitialized data and the *callback* is supposed to fill it with proper audio data. If no data is available, the buffer should be filled with zeros (e.g. by using ``outdata.fill(0)``). .. note:: In Python, assigning to an identifier merely re-binds the identifier to another object, so this *will not work* as expected:: outdata = my_data # Don't do this! To actually assign data to the buffer itself, you can use indexing, e.g.:: outdata[:] = my_data ... which fills the whole buffer, or:: outdata[:, 1] = my_channel_data ... which only fills one channel. The third argument holds the number of frames to be processed by the stream callback. This is the same as the length of the input and output buffers. The forth argument provides a CFFI structure with timestamps indicating the ADC capture time of the first sample in the input buffer (``time.inputBufferAdcTime``), the DAC output time of the first sample in the output buffer (``time.outputBufferDacTime``) and the time the callback was invoked (``time.currentTime``). These time values are expressed in seconds and are synchronised with the time base used by `time` for the associated stream. The fifth argument is a `CallbackFlags` instance indicating whether input and/or output buffers have been inserted or will be dropped to overcome underflow or overflow conditions. If an exception is raised in the *callback*, it will not be called again. If `CallbackAbort` is raised, the stream will finish as soon as possible. If `CallbackStop` is raised, the stream will continue until all buffers generated by the callback have been played. This may be useful in applications such as soundfile players where a specific duration of output is required. If another exception is raised, its traceback is printed to `sys.stderr`. Exceptions are *not* propagated to the main thread, i.e. the main Python program keeps running as if nothing had happened. .. note:: The *callback* must always fill the entire output buffer, no matter if or which exceptions are raised. If no exception is raised in the *callback*, it automatically continues to be called until `stop()`, `abort()` or `close()` are used to stop the stream. The PortAudio stream callback runs at very high or real-time priority. It is required to consistently meet its time deadlines. Do not allocate memory, access the file system, call library functions or call other functions from the stream callback that may block or take an unpredictable amount of time to complete. With the exception of `cpu_load` it is not permissible to call PortAudio API functions from within the stream callback. In order for a stream to maintain glitch-free operation the callback must consume and return audio data faster than it is recorded and/or played. PortAudio anticipates that each callback invocation may execute for a duration approaching the duration of *frames* audio frames at the stream's sampling frequency. It is reasonable to expect to be able to utilise 70% or more of the available CPU time in the PortAudio callback. However, due to buffer size adaption and other factors, not all host APIs are able to guarantee audio stability under heavy CPU load with arbitrary fixed callback buffer sizes. When high callback CPU utilisation is required the most robust behavior can be achieved by using ``blocksize=0``. finished_callback : callable, optional User-supplied function which will be called when the stream becomes inactive (i.e. once a call to `stop()` will not block). A stream will become inactive after the stream callback raises an exception or when `stop()` or `abort()` is called. For a stream providing audio output, if the stream callback raises `CallbackStop`, or `stop()` is called, the stream finished callback will not be called until all generated sample data has been played. The callback must have this signature: .. code-block:: text finished_callback() -> None clip_off : bool, optional See `default.clip_off`. dither_off : bool, optional See `default.dither_off`. never_drop_input : bool, optional See `default.never_drop_input`. prime_output_buffers_using_stream_callback : bool, optional See `default.prime_output_buffers_using_stream_callback`. """ _StreamBase.__init__(self, kind='duplex', wrap_callback='array', **_remove_self(locals())) class DeviceList(tuple): """A list with information about all available audio devices. This class is not meant to be instantiated by the user. Instead, it is returned by `query_devices()`. It contains a dictionary for each available device, holding the keys described in `query_devices()`. This class has a special string representation that is shown as return value of `query_devices()` if used in an interactive Python session. It will also be shown when using the :func:`print` function. Furthermore, it can be obtained with :func:`repr` and :class:`str() `. """ __slots__ = () def __repr__(self): idev = _get_device_id(default.device['input'], 'input') odev = _get_device_id(default.device['output'], 'output') digits = len(str(_lib.Pa_GetDeviceCount() - 1)) hostapi_names = [hostapi['name'] for hostapi in query_hostapis()] def get_mark(idx): return (' ', '>', '<', '*')[(idx == idev) + 2 * (idx == odev)] text = '\n'.join( '{mark} {idx:{dig}} {name}, {ha} ({ins} in, {outs} out)'.format( mark=get_mark(info['index']), idx=info['index'], dig=digits, name=info['name'], ha=hostapi_names[info['hostapi']], ins=info['max_input_channels'], outs=info['max_output_channels']) for info in self) return text class CallbackFlags: """Flag bits for the *status* argument to a stream *callback*. If you experience under-/overflows, you can try to increase the ``latency`` and/or ``blocksize`` settings. You should also avoid anything that could block the callback function for a long time, e.g. extensive computations, waiting for another thread, reading/writing files, network connections, etc. See Also -------- Stream Examples -------- This can be used to collect the errors of multiple *status* objects: >>> import sounddevice as sd >>> errors = sd.CallbackFlags() >>> errors |= status1 >>> errors |= status2 >>> errors |= status3 >>> # and so on ... >>> errors.input_overflow True The values may also be set and cleared by the user: >>> import sounddevice as sd >>> cf = sd.CallbackFlags() >>> cf >>> cf.input_underflow = True >>> cf >>> cf.input_underflow = False >>> cf """ __slots__ = '_flags' def __init__(self, flags=0x0): self._flags = flags def __repr__(self): flags = str(self) if not flags: flags = 'no flags set' return f'' def __str__(self): return ', '.join(name.replace('_', ' ') for name in dir(self) if not name.startswith('_') and getattr(self, name)) def __bool__(self): return bool(self._flags) def __ior__(self, other): if not isinstance(other, CallbackFlags): return NotImplemented self._flags |= other._flags return self @property def input_underflow(self): """Input underflow. In a stream opened with ``blocksize=0``, indicates that input data is all silence (zeros) because no real data is available. In a stream opened with a non-zero *blocksize*, it indicates that one or more zero samples have been inserted into the input buffer to compensate for an input underflow. This can only happen in full-duplex streams (including `playrec()`). """ return self._hasflag(_lib.paInputUnderflow) @input_underflow.setter def input_underflow(self, value): self._updateflag(_lib.paInputUnderflow, value) @property def input_overflow(self): """Input overflow. In a stream opened with ``blocksize=0``, indicates that data prior to the first sample of the input buffer was discarded due to an overflow, possibly because the stream callback is using too much CPU time. In a stream opened with a non-zero *blocksize*, it indicates that data prior to one or more samples in the input buffer was discarded. This can happen in full-duplex and input-only streams (including `playrec()` and `rec()`). """ return self._hasflag(_lib.paInputOverflow) @input_overflow.setter def input_overflow(self, value): self._updateflag(_lib.paInputOverflow, value) @property def output_underflow(self): """Output underflow. Indicates that output data (or a gap) was inserted, possibly because the stream callback is using too much CPU time. This can happen in full-duplex and output-only streams (including `playrec()` and `play()`). """ return self._hasflag(_lib.paOutputUnderflow) @output_underflow.setter def output_underflow(self, value): self._updateflag(_lib.paOutputUnderflow, value) @property def output_overflow(self): """Output overflow. Indicates that output data will be discarded because no room is available. This can only happen in full-duplex streams (including `playrec()`), but only when ``never_drop_input=True`` was specified. See `default.never_drop_input`. """ return self._hasflag(_lib.paOutputOverflow) @output_overflow.setter def output_overflow(self, value): self._updateflag(_lib.paOutputOverflow, value) @property def priming_output(self): """Priming output. Some of all of the output data will be used to prime the stream, input data may be zero. This will only take place with some of the host APIs, and only if ``prime_output_buffers_using_stream_callback=True`` was specified. See `default.prime_output_buffers_using_stream_callback`. """ return self._hasflag(_lib.paPrimingOutput) def _hasflag(self, flag): """Check a given flag.""" return bool(self._flags & flag) def _updateflag(self, flag, value): """Set/clear a given flag.""" if value: self._flags |= flag else: self._flags &= ~flag class _InputOutputPair: """Parameter pairs for device, channels, dtype and latency.""" _indexmapping = {'input': 0, 'output': 1} def __init__(self, parent, default_attr): self._pair = [None, None] self._parent = parent self._default_attr = default_attr def __getitem__(self, index): index = self._indexmapping.get(index, index) value = self._pair[index] if value is None: value = getattr(self._parent, self._default_attr)[index] return value def __setitem__(self, index, value): index = self._indexmapping.get(index, index) self._pair[index] = value def __repr__(self): return '[{0[0]!r}, {0[1]!r}]'.format(self) class default: """Get/set defaults for the *sounddevice* module. The attributes `device`, `channels`, `dtype`, `latency` and `extra_settings` accept single values which specify the given property for both input and output. However, if the property differs between input and output, pairs of values can be used, where the first value specifies the input and the second value specifies the output. All other attributes are always single values. Examples -------- >>> import sounddevice as sd >>> sd.default.samplerate = 48000 >>> sd.default.dtype ['float32', 'float32'] Different values for input and output: >>> sd.default.channels = 1, 2 A single value sets both input and output at the same time: >>> sd.default.device = 5 >>> sd.default.device [5, 5] An attribute can be set to the "factory default" by assigning ``None``: >>> sd.default.samplerate = None >>> sd.default.device = None, 4 Use `reset()` to reset all attributes: >>> 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__(). device = None, None """Index or query string of default input/output device. If not overwritten, this is queried from PortAudio. See Also -------- `default`, `query_devices()`, the *device* argument of `Stream` """ channels = _default_channels = None, None """Default number of input/output channels. See Also -------- `default`, `query_devices()`, the *channels* argument of `Stream` """ dtype = _default_dtype = 'float32', 'float32' """Default data type used for input/output samples. The types ``'float32'``, ``'int32'``, ``'int16'``, ``'int8'`` and ``'uint8'`` can be used for all streams and functions. Additionally, `play()`, `rec()` and `playrec()` support ``'float64'`` (for convenience, data is merely converted from/to ``'float32'``) and `RawInputStream`, `RawOutputStream` and `RawStream` support ``'int24'`` (packed 24 bit format, which is *not* supported in NumPy!). See Also -------- `default`, `numpy:numpy.dtype`, the *dtype* argument of `Stream` """ latency = _default_latency = 'high', 'high' """See the *latency* argument of `Stream`.""" extra_settings = _default_extra_settings = None, None """Host-API-specific input/output settings. See Also -------- AsioSettings, CoreAudioSettings, WasapiSettings """ samplerate = None """Sampling frequency in Hertz (= frames per second). See Also -------- `default`, `query_devices()` """ blocksize = _lib.paFramesPerBufferUnspecified """See the *blocksize* argument of `Stream`.""" clip_off = False """Disable clipping. Set to ``True`` to disable default clipping of out of range samples. """ dither_off = False """Disable dithering. Set to ``True`` to disable default dithering. """ never_drop_input = False """Set behavior for input overflow of full-duplex streams. Set to ``True`` to request that where possible a full duplex stream will not discard overflowed input samples without calling the stream callback. This flag is only valid for full-duplex callback streams (i.e. only `Stream` and `RawStream` and only if *callback* was specified; this includes `playrec()`) and only when used in combination with ``blocksize=0`` (the default). Using this flag incorrectly results in an error being raised. See also http://www.portaudio.com/docs/proposals/001-UnderflowOverflowHandling.html. """ prime_output_buffers_using_stream_callback = False """How to fill initial output buffers. Set to ``True`` to call the stream callback to fill initial output buffers, rather than the default behavior of priming the buffers with zeros (silence). This flag has no effect for input-only (`InputStream` and `RawInputStream`) and blocking read/write streams (i.e. if *callback* wasn't specified). See also http://www.portaudio.com/docs/proposals/020-AllowCallbackToPrimeStream.html. """ def __init__(self): for attr in self._pairs: # __setattr__() must be avoided here vars(self)[attr] = _InputOutputPair(self, '_default_' + attr) def __setattr__(self, name, value): """Only allow setting existing attributes.""" if name in self._pairs: getattr(self, name)._pair[:] = _split(value) elif name in dir(self) and name != 'reset': object.__setattr__(self, name, value) else: raise AttributeError( "'default' object has no attribute " + repr(name)) @property def _default_device(self): return (_lib.Pa_GetDefaultInputDevice(), _lib.Pa_GetDefaultOutputDevice()) @property def hostapi(self): """Index of the default host API (read-only).""" return _check(_lib.Pa_GetDefaultHostApi()) def reset(self): """Reset all attributes to their "factory default".""" vars(self).clear() self.__init__() if not hasattr(_ffi, 'I_AM_FAKE'): # This object shadows the 'default' class, except when building the docs. default = default() class PortAudioError(Exception): """This exception will be raised on PortAudio errors. Attributes ---------- args A variable length tuple containing the following elements when available: 1) A string describing the error 2) The PortAudio ``PaErrorCode`` value 3) A 3-tuple containing the host API index, host error code, and the host error message (which may be an empty string) """ def __str__(self): errormsg = self.args[0] if self.args else '' if len(self.args) > 1: errormsg = f'{errormsg} [PaErrorCode {self.args[1]}]' if len(self.args) > 2: host_api, hosterror_code, hosterror_text = self.args[2] if host_api == _lib.paHostApiNotFound: hostname = '' elif host_api < 0: hostname = f'' else: hostname = query_hostapis(host_api)['name'] errormsg = "{}: '{}' [{} error {}]".format( errormsg, hosterror_text, hostname, hosterror_code) return errormsg class CallbackStop(Exception): """Exception to be raised by the user to stop callback processing. If this is raised in the stream callback, the callback will not be invoked anymore (but all pending audio buffers will be played). See Also -------- CallbackAbort, `Stream.stop()`, Stream """ class CallbackAbort(Exception): """Exception to be raised by the user to abort callback processing. If this is raised in the stream callback, all pending buffers are discarded and the callback will not be invoked anymore. See Also -------- CallbackStop, `Stream.abort()`, Stream """ class AsioSettings: def __init__(self, channel_selectors): """ASIO-specific input/output settings. Objects of this class can be used as *extra_settings* argument to `Stream()` (and variants) or as `default.extra_settings`. Parameters ---------- channel_selectors : list of int Support for opening only specific channels of an ASIO device. *channel_selectors* is a list of integers specifying the (zero-based) channel numbers to use. The length of *channel_selectors* must match the corresponding *channels* parameter of `Stream()` (or variants), otherwise a crash may result. The values in the *channel_selectors* array must specify channels within the range of supported channels. Examples -------- Setting output channels when calling `play()`: >>> import sounddevice as sd >>> asio_out = sd.AsioSettings(channel_selectors=[12, 13]) >>> sd.play(..., extra_settings=asio_out) Setting default output channels: >>> sd.default.extra_settings = asio_out >>> sd.play(...) Setting input channels as well: >>> asio_in = sd.AsioSettings(channel_selectors=[8]) >>> sd.default.extra_settings = asio_in, asio_out >>> sd.playrec(..., channels=1, ...) """ if isinstance(channel_selectors, int): raise TypeError('channel_selectors must be a list or tuple') # int array must be kept alive! self._selectors = _ffi.new('int[]', channel_selectors) self._streaminfo = _ffi.new('PaAsioStreamInfo*', dict( size=_ffi.sizeof('PaAsioStreamInfo'), hostApiType=_lib.paASIO, version=1, flags=_lib.paAsioUseChannelSelectors, channelSelectors=self._selectors)) class CoreAudioSettings: def __init__(self, channel_map=None, change_device_parameters=False, fail_if_conversion_required=False, conversion_quality='max'): """Mac Core Audio-specific input/output settings. Objects of this class can be used as *extra_settings* argument to `Stream()` (and variants) or as `default.extra_settings`. Parameters ---------- channel_map : sequence of int, optional Support for opening only specific channels of a Core Audio device. Note that *channel_map* is treated differently between input and output channels. For input devices, *channel_map* is a list of integers specifying the (zero-based) channel numbers to use. For output devices, *channel_map* must have the same length as the number of output channels of the device. Specify unused channels with -1, and a 0-based index for any desired channels. See the example below. For additional information, see the `PortAudio documentation`__. __ https://app.assembla.com/spaces/portaudio/git/source/ master/src/hostapi/coreaudio/notes.txt change_device_parameters : bool, optional If ``True``, allows PortAudio to change things like the device's frame size, which allows for much lower latency, but might disrupt the device if other programs are using it, even when you are just querying the device. ``False`` is the default. fail_if_conversion_required : bool, optional In combination with the above flag, ``True`` causes the stream opening to fail, unless the exact sample rates are supported by the device. conversion_quality : {'min', 'low', 'medium', 'high', 'max'}, optional This sets Core Audio's sample rate conversion quality. ``'max'`` is the default. Example ------- This example assumes a device having 6 input and 6 output channels. Input is from the second and fourth channels, and output is to the device's third and fifth channels: >>> import sounddevice as sd >>> ca_in = sd.CoreAudioSettings(channel_map=[1, 3]) >>> ca_out = sd.CoreAudioSettings(channel_map=[-1, -1, 0, -1, 1, -1]) >>> sd.playrec(..., channels=2, extra_settings=(ca_in, ca_out)) """ conversion_dict = { 'min': _lib.paMacCoreConversionQualityMin, 'low': _lib.paMacCoreConversionQualityLow, 'medium': _lib.paMacCoreConversionQualityMedium, 'high': _lib.paMacCoreConversionQualityHigh, 'max': _lib.paMacCoreConversionQualityMax, } # Minimal checking on channel_map to catch errors that might # otherwise go unnoticed: if isinstance(channel_map, int): raise TypeError('channel_map must be a list or tuple') try: self._flags = conversion_dict[conversion_quality.lower()] except (KeyError, AttributeError) as e: raise ValueError('conversion_quality must be one of ' + repr(list(conversion_dict))) from e if change_device_parameters: self._flags |= _lib.paMacCoreChangeDeviceParameters if fail_if_conversion_required: self._flags |= _lib.paMacCoreFailIfConversionRequired # this struct must be kept alive! self._streaminfo = _ffi.new('PaMacCoreStreamInfo*') _lib.PaMacCore_SetupStreamInfo(self._streaminfo, self._flags) if channel_map is not None: # this array must be kept alive! self._channel_map = _ffi.new('SInt32[]', channel_map) if len(self._channel_map) == 0: raise TypeError('channel_map must not be empty') _lib.PaMacCore_SetupChannelMap(self._streaminfo, self._channel_map, len(self._channel_map)) class WasapiSettings: def __init__(self, exclusive=False, auto_convert=False, explicit_sample_format=False): """WASAPI-specific input/output settings. Objects of this class can be used as *extra_settings* argument to `Stream()` (and variants) or as `default.extra_settings`. They can also be used in `check_input_settings()` and `check_output_settings()`. Parameters ---------- exclusive : bool Exclusive mode allows to deliver audio data directly to hardware bypassing software mixing. auto_convert : bool Allow WASAPI backend to insert system-level channel matrix mixer and sample rate converter to support playback formats that do not match the current configured system settings. This is in particular required for streams not matching the system mixer sample rate. This only applies in *shared mode* and has no effect when *exclusive* is set to ``True``. explicit_sample_format : bool Force explicit sample format and do not allow PortAudio to select suitable working format. API will fail if provided sample format is not supported by audio hardware in Exclusive mode or system mixer in Shared mode. This is required for accurate native format detection. Examples -------- Setting exclusive mode when calling `play()`: >>> import sounddevice as sd >>> wasapi_exclusive = sd.WasapiSettings(exclusive=True) >>> sd.play(..., extra_settings=wasapi_exclusive) Setting exclusive mode as default: >>> sd.default.extra_settings = wasapi_exclusive >>> sd.play(...) """ flags = 0x0 if exclusive: flags |= _lib.paWinWasapiExclusive if auto_convert: flags |= _lib.paWinWasapiAutoConvert if explicit_sample_format: flags |= _lib.paWinWasapiExplicitSampleFormat self._streaminfo = _ffi.new('PaWasapiStreamInfo*', dict( size=_ffi.sizeof('PaWasapiStreamInfo'), hostApiType=_lib.paWASAPI, version=1, flags=flags, )) class _CallbackContext: """Helper class for reuse in play()/rec()/playrec() callbacks.""" blocksize = None data = None out = None frame = 0 input_channels = output_channels = None input_dtype = output_dtype = None input_mapping = output_mapping = None silent_channels = None def __init__(self, loop=False): import threading try: import numpy assert numpy # avoid "imported but unused" message (W0611) except ImportError as e: raise ImportError( 'NumPy must be installed for play()/rec()/playrec()') from e self.loop = loop self.event = threading.Event() self.status = CallbackFlags() def check_data(self, data, mapping, device): """Check data and output mapping.""" import numpy as np data = np.asarray(data) if data.ndim < 2: data = data.reshape(-1, 1) elif data.ndim > 2: raise ValueError( 'audio data to be played back must be one- or two-dimensional') frames, channels = data.shape dtype = _check_dtype(data.dtype) mapping_is_explicit = mapping is not None mapping, channels = _check_mapping(mapping, channels) if data.shape[1] == 1: pass # No problem, mono data is duplicated into arbitrary channels elif data.shape[1] != len(mapping): raise ValueError( 'number of output channels != size of output mapping') # Apparently, some PortAudio host APIs duplicate mono streams to the # first two channels, which is unexpected when specifying mapping=[1]. # 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): channels = 2 silent_channels = np.setdiff1d(np.arange(channels), mapping) if len(mapping) + len(silent_channels) != channels: raise ValueError('each channel may only appear once in mapping') self.data = data self.output_channels = channels self.output_dtype = dtype self.output_mapping = mapping self.silent_channels = silent_channels return frames def check_out(self, out, frames, channels, dtype, mapping): """Check out, frames, channels, dtype and input mapping.""" import numpy as np if out is None: if frames is None: raise TypeError('frames must be specified') if channels is None: channels = default.channels['input'] if channels is None: if mapping is None: raise TypeError( 'Unable to determine number of input channels') else: channels = len(np.atleast_1d(mapping)) if dtype is None: dtype = default.dtype['input'] try: out = np.empty((frames, channels), dtype, order='C') except TypeError as e: from numbers import Integral if not isinstance(frames, Integral): raise TypeError("'frames' must be an integer") from e if not isinstance(channels, Integral): raise TypeError("'channels' must be an integer") from e raise e else: frames, channels = out.shape dtype = out.dtype dtype = _check_dtype(dtype) mapping, channels = _check_mapping(mapping, channels) if out.shape[1] != len(mapping): raise ValueError( 'number of input channels != size of input mapping') self.out = out self.input_channels = channels self.input_dtype = dtype self.input_mapping = mapping return out, frames def callback_enter(self, status, data): """Check status and blocksize.""" self.status |= status self.blocksize = min(self.frames - self.frame, len(data)) def read_indata(self, indata): # We manually iterate over each channel in mapping because # numpy.take(..., out=...) has a bug: # https://github.com/numpy/numpy/pull/4246. # Note: using indata[:blocksize, mapping] (a.k.a. 'fancy' indexing) # would create unwanted copies (and probably memory allocations). for target, source in enumerate(self.input_mapping): # If out.dtype is 'float64', 'float32' data is "upgraded" here: self.out[self.frame:self.frame + self.blocksize, target] = \ indata[:self.blocksize, source] def write_outdata(self, outdata): # 'float64' data is cast to 'float32' here: outdata[:self.blocksize, self.output_mapping] = \ self.data[self.frame:self.frame + self.blocksize] outdata[:self.blocksize, self.silent_channels] = 0 if self.loop and self.blocksize < len(outdata): self.frame = 0 outdata = outdata[self.blocksize:] self.blocksize = min(self.frames, len(outdata)) self.write_outdata(outdata) else: outdata[self.blocksize:] = 0 def callback_exit(self): if not self.blocksize: raise CallbackAbort self.frame += self.blocksize def finished_callback(self): self.event.set() # Drop temporary audio buffers to free memory self.data = None self.out = None # Drop CFFI objects to avoid reference cycles self.stream._callback = None self.stream._finished_callback = None def start_stream(self, StreamClass, samplerate, channels, dtype, callback, blocking, **kwargs): stop() # Stop previous playback/recording self.stream = StreamClass(samplerate=samplerate, channels=channels, dtype=dtype, callback=callback, finished_callback=self.finished_callback, **kwargs) self.stream.start() global _last_callback _last_callback = self if blocking: self.wait() def wait(self, ignore_errors=True): """Wait for finished_callback. Can be interrupted with a KeyboardInterrupt. """ try: self.event.wait() finally: self.stream.close(ignore_errors) return self.status if self.status else None def _remove_self(d): """Return a copy of d without the 'self' entry.""" d = d.copy() del d['self'] return d def _check_mapping(mapping, channels): """Check mapping, obtain channels.""" import numpy as np if mapping is None: mapping = np.arange(channels) else: mapping = np.array(mapping, copy=True) mapping = np.atleast_1d(mapping) if mapping.min() < 1: raise ValueError('channel numbers must not be < 1') channels = mapping.max() mapping -= 1 # channel numbers start with 1 return mapping, channels def _check_dtype(dtype): """Check dtype.""" import numpy as np dtype = np.dtype(dtype).name if dtype in _sampleformats: pass elif dtype == 'float64': dtype = 'float32' else: raise TypeError('Unsupported data type: ' + repr(dtype)) return dtype def _get_stream_parameters(kind, device, channels, dtype, latency, extra_settings, samplerate): """Get parameters for one direction (input or output) of a stream.""" assert kind in ('input', 'output') if device is None: device = default.device device = _get_device_id(device, kind, raise_on_error=True) if channels is None: channels = default.channels channels = _select_input_or_output(channels, kind) if dtype is None: dtype = default.dtype dtype = _select_input_or_output(dtype, kind) if latency is None: latency = default.latency latency = _select_input_or_output(latency, kind) if extra_settings is None: extra_settings = default.extra_settings extra_settings = _select_input_or_output(extra_settings, kind) if samplerate is None: samplerate = default.samplerate info = query_devices(device) if channels is None: channels = info['max_' + kind + '_channels'] try: # If NumPy is available, get canonical dtype name dtype = _sys.modules['numpy'].dtype(dtype).name except Exception: pass # NumPy not available or invalid dtype (e.g. 'int24') or ... try: sampleformat = _sampleformats[dtype] except KeyError as e: raise ValueError('Invalid ' + kind + ' sample format') from e samplesize = _check(_lib.Pa_GetSampleSize(sampleformat)) if latency in ('low', 'high'): latency = info['default_' + latency + '_' + kind + '_latency'] if samplerate is None: samplerate = info['default_samplerate'] parameters = _ffi.new('PaStreamParameters*', ( device, channels, sampleformat, latency, extra_settings._streaminfo if extra_settings else _ffi.NULL)) return parameters, dtype, samplesize, samplerate def _wrap_callback(callback, *args): """Invoke callback function and check for custom exceptions.""" args = args[:-1] + (CallbackFlags(args[-1]),) try: callback(*args) except CallbackStop: return _lib.paComplete except CallbackAbort: return _lib.paAbort return _lib.paContinue def _buffer(ptr, frames, channels, samplesize): """Create a buffer object from a pointer to some memory.""" return _ffi.buffer(ptr, frames * channels * samplesize) def _array(buffer, channels, dtype): """Create NumPy array from a buffer object.""" import numpy as np data = np.frombuffer(buffer, dtype=dtype) data.shape = -1, channels return data def _split(value): """Split input/output value into two values. This can be useful for generic code that allows using the same value for input and output but also a pair of two separate values. """ if isinstance(value, (str, bytes)): # iterable, but not meant for splitting return value, value try: invalue, outvalue = value except TypeError: invalue = outvalue = value except ValueError as e: raise ValueError( f'Only single values and pairs are allowed, not {value!r}') from e return invalue, outvalue def _check(err, msg=''): """Raise PortAudioError for below-zero error codes.""" if err >= 0: return err errormsg = _ffi.string(_lib.Pa_GetErrorText(err)).decode() if msg: errormsg = f'{msg}: {errormsg}' if err == _lib.paUnanticipatedHostError: # (gh82) We grab the host error info here rather than inside # PortAudioError since _check should only ever be called after a # failing API function call. This way we can avoid any potential issues # in scenarios where multiple APIs are being used simultaneously. info = _lib.Pa_GetLastHostErrorInfo() host_api = _lib.Pa_HostApiTypeIdToHostApiIndex(info.hostApiType) hosterror_text = _ffi.string(info.errorText).decode() hosterror_info = host_api, info.errorCode, hosterror_text raise PortAudioError(errormsg, err, hosterror_info) raise PortAudioError(errormsg, err) def _select_input_or_output(value_or_pair, kind): """Given a pair (or a single value for both), select input or output.""" ivalue, ovalue = _split(value_or_pair) if kind == 'input': return ivalue elif kind == 'output': return ovalue assert False def _get_device_id(id_or_query_string, kind, raise_on_error=False): """Return device ID given space-separated substrings.""" assert kind in ('input', 'output', None) if id_or_query_string is None: id_or_query_string = default.device idev, odev = _split(id_or_query_string) if kind == 'input': id_or_query_string = idev elif kind == 'output': id_or_query_string = odev else: if idev == odev: id_or_query_string = idev else: raise ValueError('Input and output device are different: {!r}' .format(id_or_query_string)) if isinstance(id_or_query_string, int): return id_or_query_string device_list = [] for id, info in enumerate(query_devices()): if not kind or info['max_' + kind + '_channels'] > 0: hostapi_info = query_hostapis(info['hostapi']) device_list.append((id, info['name'], hostapi_info['name'])) query_string = id_or_query_string.lower() substrings = query_string.split() matches = [] exact_device_matches = [] for id, device_string, hostapi_string in device_list: full_string = device_string + ', ' + hostapi_string pos = 0 for substring in substrings: pos = full_string.lower().find(substring, pos) if pos < 0: break pos += len(substring) else: matches.append((id, full_string)) if query_string in [device_string.lower(), full_string.lower()]: exact_device_matches.append(id) if kind is None: kind = 'input/output' # Just used for error messages if not matches: if raise_on_error: raise ValueError( 'No ' + kind + ' device matching ' + repr(id_or_query_string)) else: return -1 if len(matches) > 1: if len(exact_device_matches) == 1: return exact_device_matches[0] if raise_on_error: raise ValueError('Multiple ' + kind + ' devices found for ' + repr(id_or_query_string) + ':\n' + '\n'.join(f'[{id}] {name}' for id, name in matches)) else: return -1 return matches[0][0] def _initialize(): """Initialize PortAudio. This temporarily forwards messages from stderr to ``/dev/null`` (where supported). In most cases, this doesn't have to be called explicitly, because it is automatically called with the ``import sounddevice`` statement. """ old_stderr = None try: old_stderr = _os.dup(2) devnull = _os.open(_os.devnull, _os.O_WRONLY) _os.dup2(devnull, 2) _os.close(devnull) except OSError: pass try: _check(_lib.Pa_Initialize(), 'Error initializing PortAudio') global _initialized _initialized += 1 finally: if old_stderr is not None: _os.dup2(old_stderr, 2) _os.close(old_stderr) def _terminate(): """Terminate PortAudio. In most cases, this doesn't have to be called explicitly. """ global _initialized _check(_lib.Pa_Terminate(), 'Error terminating PortAudio') _initialized -= 1 def _exit_handler(): assert _initialized >= 0 # We cleanup any open streams here since older versions of portaudio don't # manage this (see github issue #1) if _last_callback: # NB: calling stop() first is required; without it portaudio hangs when # calling close() _last_callback.stream.stop() _last_callback.stream.close() while _initialized: _terminate() _atexit.register(_exit_handler) _initialize() if __name__ == '__main__': print(query_devices()) python-sounddevice-0.5.3/sounddevice_build.py000066400000000000000000000240061507516237500214240ustar00rootroot00000000000000from cffi import FFI ffibuilder = FFI() ffibuilder.set_source('_sounddevice', None) ffibuilder.cdef(""" int Pa_GetVersion( void ); const char* Pa_GetVersionText( void ); typedef int PaError; typedef enum PaErrorCode { paNoError = 0, paNotInitialized = -10000, paUnanticipatedHostError, paInvalidChannelCount, paInvalidSampleRate, paInvalidDevice, paInvalidFlag, paSampleFormatNotSupported, paBadIODeviceCombination, paInsufficientMemory, paBufferTooBig, paBufferTooSmall, paNullCallback, paBadStreamPtr, paTimedOut, paInternalError, paDeviceUnavailable, paIncompatibleHostApiSpecificStreamInfo, paStreamIsStopped, paStreamIsNotStopped, paInputOverflowed, paOutputUnderflowed, paHostApiNotFound, paInvalidHostApi, paCanNotReadFromACallbackStream, paCanNotWriteToACallbackStream, paCanNotReadFromAnOutputOnlyStream, paCanNotWriteToAnInputOnlyStream, paIncompatibleStreamHostApi, paBadBufferPtr } PaErrorCode; const char *Pa_GetErrorText( PaError errorCode ); PaError Pa_Initialize( void ); PaError Pa_Terminate( void ); typedef int PaDeviceIndex; #define paNoDevice -1 #define paUseHostApiSpecificDeviceSpecification -2 typedef int PaHostApiIndex; PaHostApiIndex Pa_GetHostApiCount( void ); PaHostApiIndex Pa_GetDefaultHostApi( void ); typedef enum PaHostApiTypeId { paInDevelopment=0, paDirectSound=1, paMME=2, paASIO=3, paSoundManager=4, paCoreAudio=5, paOSS=7, paALSA=8, paAL=9, paBeOS=10, paWDMKS=11, paJACK=12, paWASAPI=13, paAudioScienceHPI=14 } PaHostApiTypeId; typedef struct PaHostApiInfo { int structVersion; PaHostApiTypeId type; const char *name; int deviceCount; PaDeviceIndex defaultInputDevice; PaDeviceIndex defaultOutputDevice; } PaHostApiInfo; const PaHostApiInfo * Pa_GetHostApiInfo( PaHostApiIndex hostApi ); PaHostApiIndex Pa_HostApiTypeIdToHostApiIndex( PaHostApiTypeId type ); PaDeviceIndex Pa_HostApiDeviceIndexToDeviceIndex( PaHostApiIndex hostApi, int hostApiDeviceIndex ); typedef struct PaHostErrorInfo{ PaHostApiTypeId hostApiType; long errorCode; const char *errorText; }PaHostErrorInfo; const PaHostErrorInfo* Pa_GetLastHostErrorInfo( void ); PaDeviceIndex Pa_GetDeviceCount( void ); PaDeviceIndex Pa_GetDefaultInputDevice( void ); PaDeviceIndex Pa_GetDefaultOutputDevice( void ); typedef double PaTime; typedef unsigned long PaSampleFormat; #define paFloat32 0x00000001 #define paInt32 0x00000002 #define paInt24 0x00000004 #define paInt16 0x00000008 #define paInt8 0x00000010 #define paUInt8 0x00000020 #define paCustomFormat 0x00010000 #define paNonInterleaved 0x80000000 typedef struct PaDeviceInfo { int structVersion; const char *name; PaHostApiIndex hostApi; int maxInputChannels; int maxOutputChannels; PaTime defaultLowInputLatency; PaTime defaultLowOutputLatency; PaTime defaultHighInputLatency; PaTime defaultHighOutputLatency; double defaultSampleRate; } PaDeviceInfo; const PaDeviceInfo* Pa_GetDeviceInfo( PaDeviceIndex device ); typedef struct PaStreamParameters { PaDeviceIndex device; int channelCount; PaSampleFormat sampleFormat; PaTime suggestedLatency; void *hostApiSpecificStreamInfo; } PaStreamParameters; #define paFormatIsSupported 0 PaError Pa_IsFormatSupported( const PaStreamParameters *inputParameters, const PaStreamParameters *outputParameters, double sampleRate ); typedef void PaStream; #define paFramesPerBufferUnspecified 0 typedef unsigned long PaStreamFlags; #define paNoFlag 0 #define paClipOff 0x00000001 #define paDitherOff 0x00000002 #define paNeverDropInput 0x00000004 #define paPrimeOutputBuffersUsingStreamCallback 0x00000008 #define paPlatformSpecificFlags 0xFFFF0000 typedef struct PaStreamCallbackTimeInfo{ PaTime inputBufferAdcTime; PaTime currentTime; PaTime outputBufferDacTime; } PaStreamCallbackTimeInfo; typedef unsigned long PaStreamCallbackFlags; #define paInputUnderflow 0x00000001 #define paInputOverflow 0x00000002 #define paOutputUnderflow 0x00000004 #define paOutputOverflow 0x00000008 #define paPrimingOutput 0x00000010 typedef enum PaStreamCallbackResult { paContinue=0, paComplete=1, paAbort=2 } PaStreamCallbackResult; typedef int PaStreamCallback( const void *input, void *output, unsigned long frameCount, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void *userData ); PaError Pa_OpenStream( PaStream** stream, const PaStreamParameters *inputParameters, const PaStreamParameters *outputParameters, double sampleRate, unsigned long framesPerBuffer, PaStreamFlags streamFlags, PaStreamCallback *streamCallback, void *userData ); PaError Pa_OpenDefaultStream( PaStream** stream, int numInputChannels, int numOutputChannels, PaSampleFormat sampleFormat, double sampleRate, unsigned long framesPerBuffer, PaStreamCallback *streamCallback, void *userData ); PaError Pa_CloseStream( PaStream *stream ); typedef void PaStreamFinishedCallback( void *userData ); PaError Pa_SetStreamFinishedCallback( PaStream *stream, PaStreamFinishedCallback* streamFinishedCallback ); PaError Pa_StartStream( PaStream *stream ); PaError Pa_StopStream( PaStream *stream ); PaError Pa_AbortStream( PaStream *stream ); PaError Pa_IsStreamStopped( PaStream *stream ); PaError Pa_IsStreamActive( PaStream *stream ); typedef struct PaStreamInfo { int structVersion; PaTime inputLatency; PaTime outputLatency; double sampleRate; } PaStreamInfo; const PaStreamInfo* Pa_GetStreamInfo( PaStream *stream ); PaTime Pa_GetStreamTime( PaStream *stream ); double Pa_GetStreamCpuLoad( PaStream* stream ); PaError Pa_ReadStream( PaStream* stream, void *buffer, unsigned long frames ); PaError Pa_WriteStream( PaStream* stream, const void *buffer, unsigned long frames ); signed long Pa_GetStreamReadAvailable( PaStream* stream ); signed long Pa_GetStreamWriteAvailable( PaStream* stream ); PaHostApiTypeId Pa_GetStreamHostApiType( PaStream* stream ); PaError Pa_GetSampleSize( PaSampleFormat format ); void Pa_Sleep( long msec ); /* pa_mac_core.h */ typedef int32_t SInt32; typedef struct { unsigned long size; PaHostApiTypeId hostApiType; unsigned long version; unsigned long flags; SInt32 const * channelMap; unsigned long channelMapSize; } PaMacCoreStreamInfo; void PaMacCore_SetupStreamInfo( PaMacCoreStreamInfo *data, unsigned long flags ); void PaMacCore_SetupChannelMap( PaMacCoreStreamInfo *data, const SInt32 * const channelMap, unsigned long channelMapSize ); const char *PaMacCore_GetChannelName( int device, int channelIndex, bool input ); #define paMacCoreChangeDeviceParameters 0x01 #define paMacCoreFailIfConversionRequired 0x02 #define paMacCoreConversionQualityMin 0x0100 #define paMacCoreConversionQualityMedium 0x0200 #define paMacCoreConversionQualityLow 0x0300 #define paMacCoreConversionQualityHigh 0x0400 #define paMacCoreConversionQualityMax 0x0000 #define paMacCorePlayNice 0x00 #define paMacCorePro 0x01 #define paMacCoreMinimizeCPUButPlayNice 0x0100 #define paMacCoreMinimizeCPU 0x0101 /* pa_win_waveformat.h */ typedef unsigned long PaWinWaveFormatChannelMask; /* pa_asio.h */ #define paAsioUseChannelSelectors 0x01 typedef struct PaAsioStreamInfo { unsigned long size; PaHostApiTypeId hostApiType; unsigned long version; unsigned long flags; int *channelSelectors; } PaAsioStreamInfo; /* pa_win_wasapi.h */ typedef enum PaWasapiFlags { paWinWasapiExclusive = 1, paWinWasapiRedirectHostProcessor = 2, paWinWasapiUseChannelMask = 4, paWinWasapiPolling = 8, paWinWasapiThreadPriority = 16, paWinWasapiExplicitSampleFormat = 32, paWinWasapiAutoConvert = 64 } PaWasapiFlags; typedef void (*PaWasapiHostProcessorCallback) ( void *inputBuffer, long inputFrames, void *outputBuffer, long outputFrames, void *userData); typedef enum PaWasapiThreadPriority { eThreadPriorityNone = 0, eThreadPriorityAudio, eThreadPriorityCapture, eThreadPriorityDistribution, eThreadPriorityGames, eThreadPriorityPlayback, eThreadPriorityProAudio, eThreadPriorityWindowManager } PaWasapiThreadPriority; typedef enum PaWasapiStreamCategory { eAudioCategoryOther = 0, eAudioCategoryCommunications = 3, eAudioCategoryAlerts = 4, eAudioCategorySoundEffects = 5, eAudioCategoryGameEffects = 6, eAudioCategoryGameMedia = 7, eAudioCategoryGameChat = 8, eAudioCategorySpeech = 9, eAudioCategoryMovie = 10, eAudioCategoryMedia = 11 } PaWasapiStreamCategory; typedef enum PaWasapiStreamOption { eStreamOptionNone = 0, eStreamOptionRaw = 1, eStreamOptionMatchFormat = 2 } PaWasapiStreamOption; typedef struct PaWasapiStreamInfo { unsigned long size; PaHostApiTypeId hostApiType; unsigned long version; unsigned long flags; PaWinWaveFormatChannelMask channelMask; PaWasapiHostProcessorCallback hostProcessorOutput; PaWasapiHostProcessorCallback hostProcessorInput; PaWasapiThreadPriority threadPriority; PaWasapiStreamCategory streamCategory; PaWasapiStreamOption streamOption; } PaWasapiStreamInfo; PaError PaWasapi_UpdateDeviceList(); int PaWasapi_IsLoopback( PaDeviceIndex device ); """) if __name__ == '__main__': ffibuilder.compile(verbose=True)