Module audioio.audiomodules

Query and control installation status and availability of audio modules.

list_modules() and installed_modules() let you query which audio modules are currently installed on your system.

Call missing_modules() for a list of module names that should be installed. The missing_modules_instructions() function prints installation instructions for packages you should install for better performance. For installation instructions on a specific module use installation_instruction().

By default all installed modules are used by the audioio functions. The disable_module(), enable_module() and select_module() functions allow to control which of the installed audio modules should be used by the audioio functions.

list_modules(), available_modules() and unavailable_modules() let you query which audio modules are installed and available and which modules are not available on your system.

Functions

Command line script

Run this module as a script

> python -m src.audioio.auidomodules

or, when the audioio package is installed on your system, simply run

> audiomodules

for an overview of audio packages, their installation status, and recommendations on how to install further audio packages. The output looks like this:

Status of audio packages on this machine:
-----------------------------------------

wave              is  installed (F)
ewave             is  installed (F)
scipy.io.wavfile  is  installed (F)
soundfile         is  installed (F)
wavefile          is  installed (F)
audioread         is  installed (F)
pyaudio           is  installed (D)
sounddevice       not installed (D)
simpleaudio       is  installed (D)
soundcard         is  installed (D)
ossaudiodev       is  installed (D)
winsound          not installed (D)

F: file I/O, D: audio device

There is no need to install additional audio packages.

For instructions on specific packages, run audiomodules with the name of the package supplied as argument:

> audiomodules soundfile

This produces something like this:

...
Installation instructions for the soundfile module:
---------------------------------------------------
The soundfile package is a wrapper of the sndfile library,
that supports many different audio file formats.
See http://python-soundfile.readthedocs.org for a documentation of the soundfile python wrapper
and http://www.mega-nerd.com/libsndfile for details on the sndfile library.

First, install the following packages:

sudo apt install libsndfile1 libsndfile1-dev libffi-dev

Install the soundfile module with pip:

sudo pip install SoundFile

or alternatively from your distribution's package:

sudo apt install python3-soundfile

Running

audiomodules --help

prints

usage: audiomodules [--version] [--help] [PACKAGE]

Installation status and instructions of python audio packages.

optional arguments:
  --help      show this help message and exit
  --version   show version number and exit
  PACKAGE     show installation instructions for PACKAGE

version 2.2.0 by Benda-Lab (2015-2024)

For an overview on python modules regarding file I/O see, for example, http://nbviewer.jupyter.org/github/mgeier/python-audio/blob/master/audio-files/index.ipynb

For an overview on packages for playing and recording audio, see https://realpython.com/playing-and-recording-sound-python/

Global variables

var audio_modules

Dictionary with availability of various audio modules. Keys are the module names, values are booleans. Based on this dictionary audioio employs functions of installed audio modules.

var audio_installed

List of installed audio modules.

var audio_infos

Dictionary with information about all supported audio modules. Keys are the module names, values are the informations.

var audio_instructions_linux

Dictionary with general installation instructions for linux that are needed in addition to installing some packages. Keys are the module names, values are the instructions.

var audio_instructions_windows

Dictionary with general installation instructions for windows that are needed in addition to installing some packages. Keys are the module names, values are the instructions.

var audio_pip_packages

Dictionary with pip package names of the audio modules. Keys are the module names, values are pip package names.

var audio_conda_packages

Dictionary with conda package names of the audio modules. Keys are the module names, values are conda package names, optionally with a channel specification.

var audio_deb_packages

Dictionary with Linux DEB packages of the audio modules. Keys are the module names, values are the package names.

var audio_rpm_packages

Dictionary with Linux RPM packages of the audio modules. Keys are the module names, values are the package names.

var audio_brew_packages

Dictionary with macOS homebrew packages of the audio modules. Keys are the module names, values are the package (formulae) names.

var audio_required_deb_packages

Dictionary with Linux DEB packages required for the audio modules. Keys are the module names, values are lists of string with package names.

var audio_required_rpm_packages

Dictionary with Linux RPM packages required for the audio modules. Keys are the module names, values are lists of string with package names.

var audio_required_brew_packages

Dictionary with macOS homebrew packages required for the audio modules. Keys are the module names, values are lists of string with package (formulae) names.

var audio_fileio

List of audio modules used for reading and writing audio files.

var audio_device

List of audio modules used for playing and recording sounds on audio devices.

Functions

def installed_modules(func='all')
Expand source code
def installed_modules(func='all'):
    """Installed audio modules.

    By default all installed modules are available. With
    `disable_module()`, `enable_module()` and `select_module()`
    the availability of installed modules can be controlled.

    Parameters
    ----------
    func: string
        'all': all installed audio modules.
        'fileio': installed audio modules used for file I/O.
        'device': installed audio modules used for playing and recording sounds.
    
    Returns
    -------
    mods: list of strings
        List of installed audio modules of the requested function.

    See Also
    --------
    available_modules()
    """
    if func == 'fileio':
        return [module for module in audio_fileio if module in audio_installed]
    elif func == 'device':
        return [module for module in audio_device if module in audio_installed]
    else:
        return audio_installed

Installed audio modules.

By default all installed modules are available. With disable_module(), enable_module() and select_module() the availability of installed modules can be controlled.

Parameters

func : string
'all': all installed audio modules. 'fileio': installed audio modules used for file I/O. 'device': installed audio modules used for playing and recording sounds.

Returns

mods : list of strings
List of installed audio modules of the requested function.

See Also

available_modules()

def available_modules(func='all')
Expand source code
def available_modules(func='all'):
    """Installed and enabled audio modules.

    By default all installed modules are available. With
    `disable_module()`, `enable_module()` and `select_module()`
    the availability of installed modules can be controlled.

    Parameters
    ----------
    func: string
        'all': all installed audio modules.
        'fileio': installed audio modules used for file I/O.
        'device': installed audio modules used for playing and recording sounds.
    
    Returns
    -------
    mods: list of strings
        List of available, i.e. installed and enabled, audio modules
        of the requested function.
    """
    if func == 'fileio':
        return [module for module in audio_fileio if audio_modules[module]]
    elif func == 'device':
        return [module for module in audio_device if audio_modules[module]]
    else:
        return [module for module in audio_installed if audio_modules[module]]

Installed and enabled audio modules.

By default all installed modules are available. With disable_module(), enable_module() and select_module() the availability of installed modules can be controlled.

Parameters

func : string
'all': all installed audio modules. 'fileio': installed audio modules used for file I/O. 'device': installed audio modules used for playing and recording sounds.

Returns

mods : list of strings
List of available, i.e. installed and enabled, audio modules of the requested function.
def unavailable_modules(func='all')
Expand source code
def unavailable_modules(func='all'):
    """Audio modules that are not installed and not enabled.

    Parameters
    ----------
    func: string
        'all': all installed audio modules.
        'fileio': installed audio modules used for file I/O.
        'device': installed audio modules used for playing and recording sounds.
    
    Returns
    -------
    mods: list of strings
        List of not available, i.e. not installed and not enabled, audio modules
        of the requested function.
    """
    if func == 'fileio':
        return [module for module in audio_fileio if not audio_modules[module]]
    elif func == 'device':
        return [module for module in audio_device if not audio_modules[module]]
    else:
        return [module for module in audio_modules.keys() if not audio_modules[module]]

Audio modules that are not installed and not enabled.

Parameters

func : string
'all': all installed audio modules. 'fileio': installed audio modules used for file I/O. 'device': installed audio modules used for playing and recording sounds.

Returns

mods : list of strings
List of not available, i.e. not installed and not enabled, audio modules of the requested function.
def disable_module(module=None)
Expand source code
def disable_module(module=None):
    """Disable an audio module.

    A disabled module is not used by the audioio functions and classes.
    To disable all modules except one, call `select_module()`.
    
    Parameters
    ----------
    module: string or None
        Name of the module to be disabled as it appears in `available_modules()`.
        If None disable all installed audio modules.

    See Also
    --------
    enable_module(), select_module(), available_modules(), list_modules()
    """
    if module is None:
        for module in audio_installed:
            audio_modules[module] = False
    elif module in audio_modules:
        audio_modules[module] = False

Disable an audio module.

A disabled module is not used by the audioio functions and classes. To disable all modules except one, call select_module().

Parameters

module : string or None
Name of the module to be disabled as it appears in available_modules(). If None disable all installed audio modules.

See Also

enable_module(), select_module(), available_modules(), list_modules()

def enable_module(module=None)
Expand source code
def enable_module(module=None):
    """Enable audio modules provided they are installed.
    
    Parameters
    ----------
    module: string or None
        Name of the module to be (re)enabled.
        If None enable all installed audio modules.

    See Also
    --------
    disable_module(), available_modules(), list_modules()
    """
    if module is None:
        for module in audio_installed:
            audio_modules[module] = True
    elif module in audio_modules:
        audio_modules[module] = (module in audio_installed)

Enable audio modules provided they are installed.

Parameters

module : string or None
Name of the module to be (re)enabled. If None enable all installed audio modules.

See Also

disable_module(), available_modules(), list_modules()

def select_module(module)
Expand source code
def select_module(module):
    """Select (enable) a single audio module and disable all others.

    Undo by calling `enable_module()` without arguments.
    
    Parameters
    ----------
    module: string
        Name of the module to be selected.

    Returns
    -------
    selected: bool
        False if the module can not be selected, because it is not installed.
        In this case the other modules are not disabled.

    See Also
    --------
    enable_module(), disable_module(), available_modules(), list_modules()
    """
    if module not in audio_installed:
        return False
    for mod in audio_installed:
        audio_modules[mod] = (mod == module)
    return True

Select (enable) a single audio module and disable all others.

Undo by calling enable_module() without arguments.

Parameters

module : string
Name of the module to be selected.

Returns

selected : bool
False if the module can not be selected, because it is not installed. In this case the other modules are not disabled.

See Also

enable_module(), disable_module(), available_modules(), list_modules()

def list_modules(module='all', availability=True)
Expand source code
def list_modules(module='all', availability=True):
    """Print list of all supported modules and their installation status.
    
    Modules that are not installed but are recommended are marked
    with an all uppercase "NOT installed".

    Parameters
    ----------
    module: string
        If 'all' list all modules.
        If 'fileio' list all modules used for file I/O.
        If 'device' list all modules used for playing and recording sounds.
        Otherwise list only the specified module.
    availability: bool
        Mark availability of each module by an asterisk.

    See Also
    --------
    installed_modules()
    missing_modules()
    missing_modules_instructions()
    """
    def print_module(module, missing, print_type):
        audio_avail = ''
        if availability:
            audio_avail = '* ' if audio_modules[module] else '  '
        audio_type = ''
        if print_type:
            if module in audio_fileio:
                audio_type += 'F'
            if module in audio_device:
                audio_type += 'D'
            if len(audio_type) > 0:
                audio_type = f' ({audio_type})'
        if module in audio_installed:
            print(f'{audio_avail}{module:<17s} is  installed{audio_type}')
        elif module in missing:
            print(f'{audio_avail}{module:<17s} NOT installed{audio_type}')
        else:
            print(f'{audio_avail}{module:<17s} not installed{audio_type}')

    missing = missing_modules()
    if module not in ['all', 'fileio', 'device']:
        print_module(module, missing, True)
    else:
        print_type = (module == 'all')
        modules = sorted(audio_modules.keys())
        if module in ['all', 'fileio']:
            for mod in audio_fileio:
                print_module(mod, missing, print_type)
                modules.remove(mod)
        if module in ['all', 'device']:
            for mod in audio_device:
                if mod in modules:
                    print_module(mod, missing, print_type)
                    modules.remove(mod)
        if module == 'all':
            for mod in modules:
                print_module(mod, missing, print_type)

Print list of all supported modules and their installation status.

Modules that are not installed but are recommended are marked with an all uppercase "NOT installed".

Parameters

module : string
If 'all' list all modules. If 'fileio' list all modules used for file I/O. If 'device' list all modules used for playing and recording sounds. Otherwise list only the specified module.
availability : bool
Mark availability of each module by an asterisk.

See Also

installed_modules() missing_modules() missing_modules_instructions()

def missing_modules(func='all')
Expand source code
def missing_modules(func='all'):
    """Missing audio modules that are recommended to be installed.

    Parameters
    ----------
    func: string
        'all': missing audio modules of all functions.
        'fileio': missing audio modules for file I/O.
        'device': missing audio modules for playing and recording sounds.
    
    Returns
    -------
    mods: list of strings
        List of missing audio modules of the requested function.
    """
    mods = []
    if func in ['all', 'fileio']:
        if 'soundfile' not in audio_installed and \
           'wavefile' not in audio_installed:
            mods.append('soundfile')
        if 'audioread' not in audio_installed:
            mods.append('audioread')
        if 'pydub' not in audio_installed:
            mods.append('pydub')
    if func in ['all', 'device']:
        if 'pyaudio' not in audio_installed and \
           'sounddevice' not in audio_installed:
            mods.append('sounddevice')
    return mods

Missing audio modules that are recommended to be installed.

Parameters

func : string
'all': missing audio modules of all functions. 'fileio': missing audio modules for file I/O. 'device': missing audio modules for playing and recording sounds.

Returns

mods : list of strings
List of missing audio modules of the requested function.
def missing_modules_instructions(func='all')
Expand source code
def missing_modules_instructions(func='all'):
    """Print installation instructions for missing but useful audio modules.

    Parameters
    ----------
    func: string
        'all': missing audio modules of all functions.
        'fileio': missing audio modules for file I/O.
        'device': missing audio modules for playing and recording sounds.
    """
    mods = missing_modules(func)
    if len(mods) > 0 :
        print('For better performance you should install the following modules:')
        for mod in mods:
            print()
            print(f'{mod}:')
            print('-'*(len(mod)+1))
            print(installation_instruction(mod))
    else:
        print('There is no need to install additional audio packages.')

Print installation instructions for missing but useful audio modules.

Parameters

func : string
'all': missing audio modules of all functions. 'fileio': missing audio modules for file I/O. 'device': missing audio modules for playing and recording sounds.
def installation_instruction(module)
Expand source code
def installation_instruction(module):
    """Instructions on how to install a specific audio module.

    Parameters
    ----------
    module: string
        The name of the module for which an instruction should be printed.
    
    Returns
    -------
    msg: multi-line string
        Installation instruction for the requested module.
    """
    install_package_deb = "sudo apt install"
    install_package_rpm = "dnf install"
    install_package_brew = "brew install"
    install_package = None
    package = None
    required_packages = None
    multiline = False
    instruction = None
        
    install_pip_deb = "sudo pip install"
    install_pip_rpm = "pip install"
    install_pip_osx = "pip install"
    install_pip_win = "pip install"
    install_pip = install_pip_deb

    install_conda = "conda install"

    # check operating system:
    if sys.platform[0:5] == "linux":
        if os.path.exists('/etc/redhat-release') or os.path.exists('/etc/fedora-release'):
            install_package = install_package_rpm
            install_pip = install_pip_rpm
            package = audio_rpm_packages.get(module, None)
            required_packages = audio_required_rpm_packages.get(module, None)
        else:
            install_package = install_package_deb
            package = audio_deb_packages.get(module, None)
            required_packages = audio_required_deb_packages.get(module, None)
        instruction = audio_instructions_linux.get(module, None)
    elif sys.platform == "darwin":
        install_package = install_package_brew
        install_pip = install_pip_osx
        package = audio_brew_packages.get(module, None)
        required_packages = audio_required_brew_packages.get(module, None)
        multiline = True
    elif sys.platform[0:3] == "win":
        install_package = ''
        install_pip = install_pip_win
        instruction = audio_instructions_windows.get(module, None)
    # check conda:
    conda = "CONDA_DEFAULT_ENV" in os.environ
    conda_package = audio_conda_packages.get(module, None)
    if conda:
        install_pip = install_pip.replace('sudo ', '')

    pip_package = audio_pip_packages.get(module, None)
        
    req_inst = None
    if required_packages is not None:
        if multiline:
            ps = '\n'.join([install_package + ' ' + p for p in required_packages])
        else:
            ps = install_package + ' ' + ' '.join(required_packages)
        if pip_package is None and package is None:
            req_inst = 'Install the following packages:\n\n' + ps
        else:
            req_inst = 'First, install the following packages:\n\n' + ps
    
    pip_inst = None
    if pip_package is not None:
        pip_inst = f'Install the {module} module with pip:\n\n{install_pip} {pip_package}'
        
    dist_inst = None
    if package is not None:
        if pip_inst is None:
            dist_inst = f'Install module from your distribution\'s package:\n\n{install_package} {package}'
        else:
            dist_inst = f'or alternatively from your distribution\'s package:\n\n{install_package} {package}'

    conda_inst = None
    if conda and conda_package is not None:
        conda_inst = f'Install the {module} module with conda:\n\n{install_package} {package}'
        req_inst = pip_inst = dist_inst = instruction = None

    info = audio_infos.get(module, None)

    msg = ''
    for s in [info, conda_inst, req_inst, pip_inst, dist_inst, instruction]:
        if s is not None:
            if len(msg) > 0:
                msg += '\n\n'
            msg += s
    
    return msg

Instructions on how to install a specific audio module.

Parameters

module : string
The name of the module for which an instruction should be printed.

Returns

msg : multi-line string
Installation instruction for the requested module.
def main(*args)
Expand source code
def main(*args):
    """ Command line program for listing installation status of audio modules.

    Run this module as a script
    ```
    > python -m src.audioio.auidomodules
    ```
    or, when the audioio package is installed on your system, simply run
    ```sh
    > audiomodules
    ```
    for an overview of audio packages, their installation status, and recommendations on
    how to install further audio packages.

    The '--help' argument prints out a help message:
    ```sh
    > audiomodules --help
    ```

    Parameters
    ----------
    args: list of strings
        Command line arguments as provided by sys.argv[1:]
    """
    if len(args) == 0:
        args = sys.argv[1:]
    if len(args) > 0:
        if args[0] == '--version':
            print(f'version {__version__} by Benda-Lab (2015-{__year__})')
            sys.exit(0)
        if args[0] == '--help' or args[0] == '-h':
            print('usage: audiomodules [--version] [--help] [PACKAGE]')
            print('')
            print('Installation status and instructions of python audio packages.')
            print('')
            print('optional arguments:')
            print('  --help      show this help message and exit')
            print('  --version   show version number and exit')
            print('  PACKAGE     show installation instructions for PACKAGE')
            print('')
            print(f'version {__version__} by Benda-Lab (2015-{__year__})')
            return

    print('')
    if len(args) > 0 :
        mod = args[0]
        if mod in audio_modules:
            print(f'Installation instructions for the {mod} module:')
            print('-'*(42+len(mod)))
            print(installation_instruction(mod))
            print('')
    else:
        print('Status of audio packages on this machine:')
        print('-'*41)
        print('')
        list_modules('all', False)
        print('')
        print('F: file I/O, D: audio device')
        print('')
        missing_modules_instructions()
        print('')

Command line program for listing installation status of audio modules.

Run this module as a script

> python -m src.audioio.auidomodules

or, when the audioio package is installed on your system, simply run

> audiomodules

for an overview of audio packages, their installation status, and recommendations on how to install further audio packages.

The '–help' argument prints out a help message:

> audiomodules --help

Parameters

args : list of strings
Command line arguments as provided by sys.argv[1:]