### Install PyAlsaAudio Source: https://context7.com/larsimmisch/pyalsaaudio/llms.txt Installs the PyAlsaAudio package using pip. Requires ALSA development headers, which can be installed via package managers like apt or pacman. ```bash pip install pyalsaaudio ``` -------------------------------- ### GET /pcm/info Source: https://github.com/larsimmisch/pyalsaaudio/blob/main/doc/libalsaaudio.rst Retrieves the current configuration of a PCM device as a dictionary, including hardware-derived properties and call-specific values. ```APIDOC ## GET /pcm/info ### Description Returns a dictionary containing the configuration of a PCM device. This includes properties set during instantiation, hardware-specific settings, and current device state. ### Method GET ### Endpoint /pcm/info ### Parameters None ### Request Example {} ### Response #### Success Response (200) - **name** (string) - The PCM device name. - **card_no** (integer) - The index of the sound card. - **device_no** (integer) - The index of the PCM device. - **subdevice_no** (integer) - The index of the PCM subdevice. - **state** (string) - The current name of the PCM state. - **access_type** (string) - The name of the PCM access type. #### Response Example { "name": "default", "card_no": 0, "device_no": 0, "subdevice_no": 0, "state": "PREPARED", "access_type": "RW_INTERLEAVED" } ``` -------------------------------- ### PCM.info() - Get Device Configuration Source: https://context7.com/larsimmisch/pyalsaaudio/llms.txt Retrieves a dictionary containing detailed configuration information about the PCM audio device. ```APIDOC ## PCM.info() - Get Device Configuration ### Description Returns a dictionary with comprehensive information about the PCM device configuration. ### Method `PCM.info()` ### Parameters None ### Response - **info** (dict) - A dictionary containing various PCM device parameters such as name, card number, device number, state, format, channels, rate, buffer size, etc. ### Request Example ```python import alsaaudio pcm = alsaaudio.PCM( type=alsaaudio.PCM_PLAYBACK, rate=48000, channels=2, format=alsaaudio.PCM_FORMAT_S24_LE, periodsize=512, periods=4 ) info = pcm.info() print("PCM Device Information:") print(f" Device name: {info['name']}") print(f" Card number: {info['card_no']}") print(f" Device number: {info['device_no']}") print(f" State: {info['state']}") print(f" Access type: {info['access_type']}") print(f" Format: {info['format_name']} ({info['format_description']})") print(f" Channels: {info['channels']}") print(f" Rate: {info['rate']} Hz") print(f" Period size: {info['period_size']} frames") print(f" Period time: {info['period_time']} us") print(f" Buffer size: {info['buffer_size']} frames") print(f" Buffer time: {info['buffer_time']} us") print(f" Significant bits: {info['significant_bits']}") print(f" Nominal bits: {info['nominal_bits']}") print(f" Physical bits: {info['physical_bits']}") print(f" Can pause: {info['can_pause']}") print(f" Can resume: {info['can_resume']}") pcm.close() ``` ``` -------------------------------- ### Manage Capture/Recording Switches Source: https://context7.com/larsimmisch/pyalsaaudio/llms.txt Provides examples for enabling or disabling the recording/capture state on mixer controls, useful for input devices like microphones. ```python import alsaaudio try: mixer = alsaaudio.Mixer('Capture') rec_status = mixer.getrec() mixer.setrec(1) # Enable recording mixer.setrec(0, channel=0) # Disable on channel 0 mixer.close() except alsaaudio.ALSAAudioError as e: print(f"Capture control not available: {e}") ``` -------------------------------- ### PCM.avail() - Get Available Frames Source: https://context7.com/larsimmisch/pyalsaaudio/llms.txt Returns the number of frames available for reading (capture) or writing (playback) in the PCM buffer. ```APIDOC ## PCM.avail() - Get Available Frames ### Description Returns the number of frames available for reading (capture) or writing (playback). ### Method `PCM.avail()` ### Parameters None ### Response - **available_frames** (int) - The number of frames available. ### Request Example ```python import alsaaudio # For playback: returns free frames in buffer pcm_play = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK, periodsize=1024) available = pcm_play.avail() print(f"Frames available for writing: {available}") pcm_play.close() # For capture: returns filled frames in buffer pcm_cap = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, periodsize=1024) available = pcm_cap.avail() print(f"Frames available for reading: {available}") pcm_cap.close() ``` ``` -------------------------------- ### Manage Mixer Volume Levels Source: https://context7.com/larsimmisch/pyalsaaudio/llms.txt Demonstrates how to get and set volume levels for mixer controls using percentage, raw, or dB units. It also shows how to query volume ranges and handle specific channels. ```python import alsaaudio mixer = alsaaudio.Mixer('Master') # Get current volume (percentage by default) volumes = mixer.getvolume() print(f"Current volume: {volumes}") # Get volume in different units volumes_raw = mixer.getvolume(units=alsaaudio.VOLUME_UNITS_RAW) volumes_db = mixer.getvolume(units=alsaaudio.VOLUME_UNITS_DB) print(f"Raw volume: {volumes_raw}") print(f"Volume in dB: {[v/100.0 for v in volumes_db]}") # Get volume range vol_min, vol_max = mixer.getrange(units=alsaaudio.VOLUME_UNITS_PERCENTAGE) print(f"Volume range: {vol_min}% - {vol_max}%") # Set volume for all channels mixer.setvolume(80) # Set volume for a specific channel (0 = left, 1 = right) mixer.setvolume(70, channel=0) mixer.setvolume(90, channel=1) # Set volume using dB mixer.setvolume(-1000, units=alsaaudio.VOLUME_UNITS_DB) mixer.close() ``` -------------------------------- ### Mixer Control Example - Shell Source: https://github.com/larsimmisch/pyalsaaudio/blob/main/doc/libalsaaudio.rst Demonstrates how to interact with ALSA mixer controls from the command line using a Python script. It shows listing controls, displaying a control's settings, and setting a control's parameter like 'mute' or a volume level. ```shell $ ./mixertest.py Available mixer controls: 'Master' 'Master Mono' 'Headphone' 'PCM' 'Line' 'Line In->Rear Out' 'CD' 'Mic' 'PC Speaker' 'Aux' 'Mono Output Select' 'Capture' 'Mix' 'Mix Mono' $ ./mixertest.py Master Mixer name: 'Master' Capabilities: Playback Volume Playback Mute Channel 0 volume: 61% Channel 1 volume: 61% $ ./mixertest.py Master mute $ ./mixertest.py Master 40 ``` -------------------------------- ### Play Audio Data with PCM.write() Source: https://context7.com/larsimmisch/pyalsaaudio/llms.txt Demonstrates how to write audio data to a playback device using PyAlsaAudio's PCM.write() method. Includes examples for playing a WAV file and generating a sine wave, handling different audio formats and buffer underruns. ```python import alsaaudio import wave import struct from math import sin, pi # Example 1: Play a WAV file def play_wav(filename, device='default'): with wave.open(filename, 'rb') as wf: sample_width = wf.getsampwidth() if sample_width == 1: format = alsaaudio.PCM_FORMAT_U8 elif sample_width == 2: format = alsaaudio.PCM_FORMAT_S16_LE elif sample_width == 3: format = alsaaudio.PCM_FORMAT_S24_3LE elif sample_width == 4: format = alsaaudio.PCM_FORMAT_S32_LE else: raise ValueError(f"Unsupported sample width: {sample_width}") periodsize = wf.getframerate() // 8 pcm = alsaaudio.PCM( type=alsaaudio.PCM_PLAYBACK, channels=wf.getnchannels(), rate=wf.getframerate(), format=format, periodsize=periodsize, device=device ) data = wf.readframes(periodsize) while data: result = pcm.write(data) if result < 0: print("Buffer underrun occurred!") data = wf.readframes(periodsize) pcm.drain() pcm.close() # Example 2: Generate and play a sine wave def play_sine(frequency=440, duration=2.0, device='default'): rate = 48000 channels = 2 periodsize = 1024 pcm = alsaaudio.PCM( type=alsaaudio.PCM_PLAYBACK, channels=channels, rate=rate, format=alsaaudio.PCM_FORMAT_S16_LE, periodsize=periodsize, device=device ) total_frames = int(rate * duration) frames_written = 0 while frames_written < total_frames: frames_to_write = min(periodsize, total_frames - frames_written) samples = [] for i in range(frames_to_write): t = (frames_written + i) / rate sample = int(32767 * sin(2 * pi * frequency * t)) samples.extend([sample] * channels) data = struct.pack(f'{len(samples)}h', *samples) result = pcm.write(data) if result < 0: print("Buffer underrun!") frames_written += frames_to_write pcm.drain() pcm.close() # play_wav('audio.wav') # play_sine(440, 2.0) ``` -------------------------------- ### Capture Audio Data with PCM.read() Source: https://context7.com/larsimmisch/pyalsaaudio/llms.txt Shows how to capture audio data from a capture device using PyAlsaAudio's PCM.read() method. Includes examples for recording audio to a file and implementing a real-time audio level meter, handling buffer overruns and different capture modes. ```python import alsaaudio import time import struct # Example 1: Record audio to a file def record_audio(filename, duration=5.0, device='default'): rate = 44100 channels = 1 periodsize = 160 pcm = alsaaudio.PCM( type=alsaaudio.PCM_CAPTURE, mode=alsaaudio.PCM_NONBLOCK, channels=channels, rate=rate, format=alsaaudio.PCM_FORMAT_S16_LE, periodsize=periodsize, device=device ) with open(filename, 'wb') as f: start_time = time.time() while time.time() - start_time < duration: length, data = pcm.read() if length < 0: print("Capture buffer overrun! Continuing...") elif length > 0: f.write(data) else: time.sleep(0.001) pcm.close() print(f"Recorded {duration} seconds to {filename}") print(f"Play with: aplay -r {rate} -f S16_LE -c {channels} {filename}") # Example 2: Real-time audio level meter def audio_level_meter(duration=10.0, device='default'): rate = 44100 channels = 1 periodsize = 1024 pcm = alsaaudio.PCM( type=alsaaudio.PCM_CAPTURE, mode=alsaaudio.PCM_NORMAL, channels=channels, rate=rate, format=alsaaudio.PCM_FORMAT_S16_LE, periodsize=periodsize, device=device ) start_time = time.time() while time.time() - start_time < duration: length, data = pcm.read() if length > 0: samples = struct.unpack(f'{length}h', data) rms = (sum(s**2 for s in samples) / len(samples)) ** 0.5 level = int(50 * rms / 32768) print(f"\rLevel: {'#' * level}{' ' * (50 - level)}", end='', flush=True) pcm.close() print() # record_audio('recording.raw', duration=5.0) # audio_level_meter(duration=10.0) ``` -------------------------------- ### Get Supported Formats - Pyalsa Source: https://github.com/larsimmisch/pyalsaaudio/blob/main/doc/libalsaaudio.rst Retrieves a dictionary of supported audio formats. The keys are the format names (strings), and the values are their corresponding integer codes. ```python supported_formats = PCM.getformats() # Returns a dictionary {format_name: format_code} ``` -------------------------------- ### Get ALSA Library Version (Python) Source: https://context7.com/larsimmisch/pyalsaaudio/llms.txt Retrieves the version string of the ALSA library being used by PyAlsaAudio via the alsaaudio.asoundlib_version() function. ```python import alsaaudio version = alsaaudio.asoundlib_version() print(f"ALSA library version: {version}") ``` -------------------------------- ### PCM Methods Source: https://github.com/larsimmisch/pyalsaaudio/blob/main/doc/libalsaaudio.rst This section covers the methods available for interacting with a PCM object, including dumping information, retrieving type and mode, and getting the card name. ```APIDOC ## PCM Methods ### Description This section describes the methods available on a PCM object for retrieving information about its configuration and capabilities. ### Methods - **PCM.dumpinfo()** - Description: Dumps the PCM object's configured parameters to standard output. - Usage: `pcm_object.dumpinfo()` - **PCM.pcmtype() -> int** - Description: Returns the type of the PCM object. Possible values are :const:`PCM_CAPTURE` or :const:`PCM_PLAYBACK`. - Usage: `pcm_object.pcmtype()` - **PCM.pcmmode() -> int** - Description: Returns the mode of the PCM object. Possible values are :const:`PCM_NONBLOCK`, :const:`PCM_ASYNC`, or :const:`PCM_NORMAL`. - Usage: `pcm_object.pcmmode()` - **PCM.cardname() -> string** - Description: Returns the name of the sound card used by this PCM object. - Usage: `pcm_object.cardname()` ``` -------------------------------- ### Get PCM Device Configuration with alsaaudio Source: https://context7.com/larsimmisch/pyalsaaudio/llms.txt Retrieves detailed configuration information about an ALSA PCM device using alsaaudio.PCM.info(). The returned dictionary includes details like device name, card number, format, rate, and buffer settings. Requires the alsaaudio library. ```python import alsaaudio pcm = alsaaudio.PCM( type=alsaaudio.PCM_PLAYBACK, rate=48000, channels=2, format=alsaaudio.PCM_FORMAT_S24_LE, periodsize=512, periods=4 ) info = pcm.info() print("PCM Device Information:") print(f" Device name: {info['name']}") print(f" Card number: {info['card_no']}") print(f" Device number: {info['device_no']}") print(f" State: {info['state']}") print(f" Access type: {info['access_type']}") print(f" Format: {info['format_name']} ({info['format_description']})") print(f" Channels: {info['channels']}") print(f" Rate: {info['rate']} Hz") print(f" Period size: {info['period_size']} frames") print(f" Period time: {info['period_time']} us") print(f" Buffer size: {info['buffer_size']} frames") print(f" Buffer time: {info['buffer_time']} us") print(f" Significant bits: {info['significant_bits']}") print(f" Nominal bits: {info['nominal_bits']}") print(f" Physical bits: {info['physical_bits']}") print(f" Can pause: {info['can_pause']}") print(f" Can resume: {info['can_resume']}") pcm.close() ``` -------------------------------- ### Get Mixer Volume Capabilities (Python) Source: https://github.com/larsimmisch/pyalsaaudio/blob/main/doc/libalsaaudio.rst Returns a list of volume control capabilities for an ALSA mixer. These capabilities define whether the mixer can control volume, and if so, whether it applies to all channels ('Joined Volume'), playback, capture, or a combination. ```python import alsaaudio m = alsaaudio.Mixer() print(m.volumecap()) ``` -------------------------------- ### Get Device Information Source: https://context7.com/larsimmisch/pyalsaaudio/llms.txt Retrieves and prints detailed information about the PCM playback device, including its name, sample rate, number of channels, audio format, period size, and buffer size. ```APIDOC ## Get Device Information ### Description Retrieves and prints detailed information about the PCM playback device. ### Method N/A (Function call within Python script) ### Endpoint N/A ### Parameters N/A ### Request Example ```python # Assuming pcm_playback is an initialized alsaaudio.PCM object info = pcm_playback.info() print(f"Device: {info['name']}") print(f"Rate: {info['rate']} Hz") print(f"Channels: {info['channels']}") print(f"Format: {info['format_name']}") print(f"Period size: {info['period_size']} frames") print(f"Buffer size: {info['buffer_size']} frames") pcm_playback.close() pcm_capture.close() ``` ### Response #### Success Response (Output) Prints device information to the console. #### Response Example ``` Device: hw:0,0 Rate: 48000 Hz Channels: 2 Format: S16_LE Period size: 1024 frames Buffer size: 2048 frames ``` ``` -------------------------------- ### Get Supported Rate Bounds - Pyalsa Source: https://github.com/larsimmisch/pyalsaaudio/blob/main/doc/libalsaaudio.rst Retrieves the minimum and maximum supported sample rates for the audio device. This provides the range of frequencies the device can process. ```python rate_bounds = PCM.getratebounds() # Returns a tuple of two integers: (min_rate, max_rate) ``` -------------------------------- ### Get Supported Channel Counts - Pyalsa Source: https://github.com/larsimmisch/pyalsaaudio/blob/main/doc/libalsaaudio.rst Retrieves a list of supported channel counts for the audio device. This method returns the various channel configurations the device can handle. ```python supported_channels = PCM.getchannels() # Returns a list of integers representing supported channel counts ``` -------------------------------- ### Get PCM Stream State with alsaaudio Source: https://context7.com/larsimmisch/pyalsaaudio/llms.txt Retrieves and displays the current state of an ALSA PCM stream using alsaaudio.PCM.state(). It maps integer state constants to human-readable names. Requires the alsaaudio library. ```python import alsaaudio pcm = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK) state = pcm.state() # State constants: state_names = { alsaaudio.PCM_STATE_OPEN: "OPEN", alsaaudio.PCM_STATE_SETUP: "SETUP", alsaaudio.PCM_STATE_PREPARED: "PREPARED", alsaaudio.PCM_STATE_RUNNING: "RUNNING", alsaaudio.PCM_STATE_XRUN: "XRUN (underrun/overrun)", alsaaudio.PCM_STATE_DRAINING: "DRAINING", alsaaudio.PCM_STATE_PAUSED: "PAUSED", alsaaudio.PCM_STATE_SUSPENDED: "SUSPENDED", alsaaudio.PCM_STATE_DISCONNECTED: "DISCONNECTED", } print(f"Current state: {state_names.get(state, 'UNKNOWN')}") pcm.close() ``` -------------------------------- ### Get Device Information with PyAlsaAudio Source: https://context7.com/larsimmisch/pyalsaaudio/llms.txt Retrieves and prints detailed information about the audio playback device, such as name, rate, channels, format, period size, and buffer size. It also demonstrates closing the PCM playback and capture devices. ```python import alsaaudio pcm_playback = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK) pcm_capture = alsaaudio.PCM(alsaaudio.PCM_CAPTURE) # Get device information info = pcm_playback.info() print(f"Device: {info['name']}") print(f"Rate: {info['rate']} Hz") print(f"Channels: {info['channels']}") print(f"Format: {info['format_name']}") print(f"Period size: {info['period_size']} frames") print(f"Buffer size: {info['buffer_size']} frames") pcm_playback.close() pcm_capture.close() ``` -------------------------------- ### Get Available Frames for PCM Stream with alsaaudio Source: https://context7.com/larsimmisch/pyalsaaudio/llms.txt Checks the number of frames available for writing (playback) or reading (capture) in an ALSA PCM stream using alsaaudio.PCM.avail(). Useful for managing buffer space in non-blocking audio operations. Requires the alsaaudio library. ```python import alsaaudio # For playback: returns free frames in buffer pcm_play = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK, periodsize=1024) available = pcm_play.avail() print(f"Frames available for writing: {available}") pcm_play.close() # For capture: returns filled frames in buffer pcm_cap = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, periodsize=1024) available = pcm_cap.avail() print(f"Frames available for reading: {available}") pcm_cap.close() ``` -------------------------------- ### Get Mixer Switch Capabilities (Python) Source: https://github.com/larsimmisch/pyalsaaudio/blob/main/doc/libalsaaudio.rst Returns a list of switch capabilities for a specific ALSA mixer. These capabilities indicate whether the mixer can perform actions like muting channels, playback, or capture. The list can include values such as 'Mute', 'Joined Mute', 'Playback Mute', etc. ```python import alsaaudio m = alsaaudio.Mixer() print(m.switchcap()) ``` -------------------------------- ### Get Volume Range (Python) Source: https://github.com/larsimmisch/pyalsaaudio/blob/main/doc/libalsaaudio.rst Returns the volume range (minimum and maximum values) for an ALSA mixer. The range can be specified in different units (percentage, raw, dB) and for either playback or capture channels. ```python import alsaaudio m = alsaaudio.Mixer() min_vol, max_vol = m.getrange() print(f'Volume range: {min_vol} - {max_vol}') min_vol_db, max_vol_db = m.getrange(units=alsaaudio.VOLUME_UNITS_DB) print(f'Volume range (dB): {min_vol_db} - {max_vol_db}') ``` -------------------------------- ### Get Supported Sample Rates - Pyalsa Source: https://github.com/larsimmisch/pyalsaaudio/blob/main/doc/libalsaaudio.rst Retrieves the sample rates supported by the audio device. The return format varies: a single rate, a range, or a list of discrete rates. ```python supported_rates = PCM.getrates() # Returns rate (int), (min_rate, max_rate) tuple, or list of rates ``` -------------------------------- ### Get Mixer Name and ID (Python) Source: https://github.com/larsimmisch/pyalsaaudio/blob/main/doc/libalsaaudio.rst Retrieves the name and ID of the ALSA mixer controlled by the Mixer object. The name is a string like 'Master' or 'PCM', and the ID is an integer. ```python import alsaaudio m = alsaaudio.Mixer() print(m.cardname()) print(m.mixerid()) ``` -------------------------------- ### Get Poll Descriptors for PCM Stream with alsaaudio Source: https://context7.com/larsimmisch/pyalsaaudio/llms.txt Obtains file descriptors for an ALSA PCM stream using alsaaudio.PCM.polldescriptors() to enable non-blocking I/O with select.poll(). Demonstrates registering descriptors, waiting for events, and reading data. Requires alsaaudio and select libraries. ```python import alsaaudio import select pcm = alsaaudio.PCM( type=alsaaudio.PCM_CAPTURE, mode=alsaaudio.PCM_NONBLOCK, channels=1, rate=44100, format=alsaaudio.PCM_FORMAT_S16_LE, periodsize=1024 ) # Get poll descriptors descriptors = pcm.polldescriptors() print(f"Poll descriptors: {descriptors}") # Use with select.poll() poll = select.poll() for fd, eventmask in descriptors: poll.register(fd, eventmask) # Wait for data to be available print("Waiting for audio data...") events = poll.poll(5000) # 5 second timeout if events: # Process revents to check what happened revents = pcm.polldescriptors_revents([(fd, event) for fd, event in events]) if revents & select.POLLIN: length, data = pcm.read() print(f"Read {length} frames") else: print("Timeout - no data available") pcm.close() ``` -------------------------------- ### Get Enumerated Control (Python) Source: https://github.com/larsimmisch/pyalsaaudio/blob/main/doc/libalsaaudio.rst For enumerated controls, this method returns the currently selected item and a list of all available items. It's useful for mixers with discrete options, like selecting an output source. Returns an empty tuple if the mixer is not an enumerated control. ```python import alsaaudio m = alsaaudio.Mixer('Mono Output Select') print(m.getenum()) ``` -------------------------------- ### Get Recording Status - pyalsaaudio Mixer Source: https://github.com/larsimmisch/pyalsaaudio/blob/main/doc/libalsaaudio.rst Returns a list indicating the current recording status for each channel. 0 means not recording, and 1 means recording. This method requires the mixer to have capture switch capabilities. ```python mixer.getrec() ``` -------------------------------- ### Get Current Volume (Python) Source: https://github.com/larsimmisch/pyalsaaudio/blob/main/doc/libalsaaudio.rst Retrieves the current volume settings for each channel of an ALSA mixer. The volume is returned as a list of integers, with the meaning of the integers determined by the specified units (percentage, raw, dB) and PCM type (playback or capture). ```python import alsaaudio m = alsaaudio.Mixer() current_volume = m.getvolume() print(f'Current volume: {current_volume}') current_volume_db = m.getvolume(units=alsaaudio.VOLUME_UNITS_DB) print(f'Current volume (dB): {current_volume_db}') ``` -------------------------------- ### Initialize Mixer Control with alsaaudio Source: https://context7.com/larsimmisch/pyalsaaudio/llms.txt Demonstrates initializing the alsaaudio.Mixer class to control audio volume and mute settings. Shows how to open the 'Master' mixer on the default device and retrieve its name and card information. Requires the alsaaudio library. ```python import alsaaudio # Open the Master mixer on the default device master = alsaaudio.Mixer('Master') print(f"Mixer: {master.mixer()}") print(f"Card: {master.cardname()}") # Open a specific mixer on a specific card ``` -------------------------------- ### Initialize PCM Object Source: https://github.com/larsimmisch/pyalsaaudio/blob/main/doc/libalsaaudio.rst Shows how to instantiate a PCM object for audio playback or recording with specific configuration parameters like sample rate and channels. ```python import alsaaudio # Initialize a PCM device for playback pcm = alsaaudio.PCM(type=alsaaudio.PCM_PLAYBACK, mode=alsaaudio.PCM_NORMAL, rate=44100, channels=2, format=alsaaudio.PCM_FORMAT_S16_LE) ``` -------------------------------- ### List ALSA Devices and Mixers Source: https://github.com/larsimmisch/pyalsaaudio/blob/main/doc/libalsaaudio.rst Demonstrates how to retrieve lists of available PCM devices, sound cards, and mixer controls using the alsaaudio module. ```python import alsaaudio # List playback devices print(alsaaudio.pcms(alsaaudio.PCM_PLAYBACK)) # List available cards print(alsaaudio.cards()) # List mixers for the default device print(alsaaudio.mixers()) ``` -------------------------------- ### PCM Class Constructor (Python) Source: https://context7.com/larsimmisch/pyalsaaudio/llms.txt Demonstrates creating PCM device objects for audio playback and capture using the alsaaudio.PCM class. Allows configuration of type, mode, rate, channels, format, and period size. ```python import alsaaudio # Create a playback device with default settings # Default: 44100 Hz, stereo, 16-bit little-endian pcm_playback = alsaaudio.PCM( type=alsaaudio.PCM_PLAYBACK, mode=alsaaudio.PCM_NORMAL, device='default' ) # Create a capture device with custom settings pcm_capture = alsaaudio.PCM( type=alsaaudio.PCM_CAPTURE, mode=alsaaudio.PCM_NONBLOCK, rate=48000, channels=1, format=alsaaudio.PCM_FORMAT_S16_LE, periodsize=1024, periods=4, device='default' ) # Available formats: # PCM_FORMAT_S8, PCM_FORMAT_U8 # PCM_FORMAT_S16_LE, PCM_FORMAT_S16_BE, PCM_FORMAT_U16_LE, PCM_FORMAT_U16_BE # PCM_FORMAT_S24_LE, PCM_FORMAT_S24_BE, PCM_FORMAT_S24_3LE, PCM_FORMAT_S24_3BE # PCM_FORMAT_S32_LE, PCM_FORMAT_S32_BE # PCM_FORMAT_FLOAT_LE, PCM_FORMAT_FLOAT_BE # PCM_FORMAT_FLOAT64_LE, PCM_FORMAT_FLOAT64_BE ``` -------------------------------- ### PCM.polldescriptors() - Get Poll Descriptors Source: https://context7.com/larsimmisch/pyalsaaudio/llms.txt Retrieves file descriptors that can be used with the `select.poll()` function for non-blocking I/O operations on the PCM stream. ```APIDOC ## PCM.polldescriptors() - Get Poll Descriptors ### Description Returns file descriptors for use with `select.poll()` for non-blocking I/O. ### Method `PCM.polldescriptors()` ### Parameters None ### Response - **descriptors** (list of tuples) - A list where each tuple contains a file descriptor and its associated event mask. ### Request Example ```python import alsaaudio import select pcm = alsaaudio.PCM( type=alsaaudio.PCM_CAPTURE, mode=alsaaudio.PCM_NONBLOCK, channels=1, rate=44100, format=alsaaudio.PCM_FORMAT_S16_LE, periodsize=1024 ) # Get poll descriptors descriptors = pcm.polldescriptors() print(f"Poll descriptors: {descriptors}") # Use with select.poll() poll = select.poll() for fd, eventmask in descriptors: poll.register(fd, eventmask) # Wait for data to be available print("Waiting for audio data...") events = poll.poll(5000) # 5 second timeout if events: # Process revents to check what happened revents = pcm.polldescriptors_revents([(fd, event) for fd, event in events]) if revents & select.POLLIN: length, data = pcm.read() print(f"Read {length} frames") else: print("Timeout - no data available") pcm.close() ``` ``` -------------------------------- ### List Available ALSA PCMs - Python Source: https://github.com/larsimmisch/pyalsaaudio/blob/main/doc/libalsaaudio.rst Imports the alsaaudio library and prints a list of available PCM devices on the system. This is useful for identifying card names for other ALSA operations. ```python import alsaaudio alsaaudio.pcms() ``` -------------------------------- ### Get PCM Card Name - Pyalsa Source: https://github.com/larsimmisch/pyalsaaudio/blob/main/doc/libalsaaudio.rst Retrieves the name of the sound card associated with the PCM object. This is useful for identifying the specific audio hardware being used. ```python card_name = PCM.cardname() # Returns the name of the sound card ``` -------------------------------- ### Implement Real-Time Audio Loopback Source: https://context7.com/larsimmisch/pyalsaaudio/llms.txt Captures audio from an input device and writes it immediately to an output device. This is useful for testing latency and audio processing pipelines. ```python import alsaaudio def audio_loopback(device='default', duration_seconds=10): rate = 44100 channels = 2 periodsize = 256 capture = alsaaudio.PCM(type=alsaaudio.PCM_CAPTURE, mode=alsaaudio.PCM_NORMAL, channels=channels, rate=rate, format=alsaaudio.PCM_FORMAT_S16_LE, periodsize=periodsize, device=device) playback = alsaaudio.PCM(type=alsaaudio.PCM_PLAYBACK, mode=alsaaudio.PCM_NORMAL, channels=channels, rate=rate, format=alsaaudio.PCM_FORMAT_S16_LE, periodsize=periodsize, device=device) loops = int(rate * duration_seconds / periodsize) for _ in range(loops): length, data = capture.read() if length > 0: playback.write(data) capture.close() playback.close() ``` -------------------------------- ### Create a Volume Controller Class Source: https://context7.com/larsimmisch/pyalsaaudio/llms.txt A wrapper class for the alsaaudio.Mixer object to simplify volume adjustments, muting, and state management. ```python import alsaaudio class VolumeController: def __init__(self, control='Master', device='default'): self.mixer = alsaaudio.Mixer(control, device=device) def get_volume(self): volumes = self.mixer.getvolume() return sum(volumes) // len(volumes) def set_volume(self, percent): self.mixer.setvolume(max(0, min(100, percent))) def toggle_mute(self): mutes = self.mixer.getmute() self.mixer.setmute(0 if mutes[0] else 1) return not mutes[0] def close(self): self.mixer.close() ``` -------------------------------- ### PCM.state() - Get Stream State Source: https://context7.com/larsimmisch/pyalsaaudio/llms.txt Retrieves the current state of the PCM stream. The state is returned as an integer constant, which can be mapped to human-readable names using the provided dictionary. ```APIDOC ## PCM.state() - Get Stream State ### Description Returns the current state of the PCM stream as an integer constant. ### Method `PCM.state()` ### Parameters None ### Response - **state** (int) - An integer representing the current state of the PCM stream (e.g., `alsaaudio.PCM_STATE_RUNNING`). ### Response Example ```python import alsaaudio pcm = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK) state = pcm.state() state_names = { alsaaudio.PCM_STATE_OPEN: "OPEN", alsaaudio.PCM_STATE_SETUP: "SETUP", alsaaudio.PCM_STATE_PREPARED: "PREPARED", alsaaudio.PCM_STATE_RUNNING: "RUNNING", alsaaudio.PCM_STATE_XRUN: "XRUN (underrun/overrun)", alsaaudio.PCM_STATE_DRAINING: "DRAINING", alsaaudio.PCM_STATE_PAUSED: "PAUSED", alsaaudio.PCM_STATE_SUSPENDED: "SUSPENDED", alsaaudio.PCM_STATE_DISCONNECTED: "DISCONNECTED", } print(f"Current state: {state_names.get(state, 'UNKNOWN')}") pcm.close() ``` ``` -------------------------------- ### Control PCM Stream Playback with alsaaudio Source: https://context7.com/larsimmisch/pyalsaaudio/llms.txt Demonstrates controlling ALSA PCM stream playback using pause(), drop(), and drain() methods. Includes generating and writing audio data, pausing/resuming playback, and waiting for buffered audio to complete. Requires alsaaudio, time, struct, and math libraries. ```python import alsaaudio import time import struct from math import sin, pi pcm = alsaaudio.PCM( type=alsaaudio.PCM_PLAYBACK, rate=48000, channels=2, format=alsaaudio.PCM_FORMAT_S16_LE, periodsize=1024 ) # Generate some audio data (1 second of 440 Hz sine) rate = 48000 samples = [] for i in range(rate): sample = int(32767 * sin(2 * pi * 440 * i / rate)) samples.extend([sample, sample]) # Stereo data = struct.pack(f'{len(samples)}h', *samples) # Write data in chunks chunk_size = 1024 * 4 # 1024 frames * 2 channels * 2 bytes for i in range(0, len(data), chunk_size): pcm.write(data[i:i+chunk_size]) # Pause playback pcm.pause(True) print("Paused for 1 second...") time.sleep(1) # Resume playback pcm.pause(False) print("Resumed") # Drain - wait for all buffered audio to play pcm.drain() print("Playback complete") # Or use drop() to immediately stop and discard buffered audio # pcm.drop() pcm.close() ``` -------------------------------- ### Mixer Volume Control API Source: https://github.com/larsimmisch/pyalsaaudio/blob/main/doc/libalsaaudio.rst APIs for managing volume levels on ALSA mixers, including getting volume ranges, current volumes, and setting new volume levels. ```APIDOC ## Mixer.getrange(pcmtype: int = PCM_PLAYBACK, units: int = VOLUME_UNITS_RAW) ### Description Return the volume range of the ALSA mixer controlled by this object. ### Method GET ### Endpoint /mixer/range ### Parameters #### Query Parameters - **pcmtype** (int) - Optional - Specifies whether to get the range for playback or capture. Use constants like `PCM_PLAYBACK` or `PCM_CAPTURE`. Defaults to `PCM_PLAYBACK`. - **units** (int) - Optional - Specifies the units for the volume range. Use constants like `VOLUME_UNITS_PERCENTAGE`, `VOLUME_UNITS_RAW`, or `VOLUME_UNITS_DB`. Defaults to `VOLUME_UNITS_RAW`. ### Response #### Success Response (200) - **min_volume** (int) - The minimum volume value. - **max_volume** (int) - The maximum volume value. ### Response Example ```json { "min_volume": 0, "max_volume": 100 } ``` ## Mixer.getvolume(pcmtype: int = PCM_PLAYBACK, units: int = VOLUME_UNITS_PERCENTAGE) ### Description Returns a list with the current volume settings for each channel. ### Method GET ### Endpoint /mixer/volume ### Parameters #### Query Parameters - **pcmtype** (int) - Optional - Specifies whether to get the volume for playback or capture. Use constants like `PCM_PLAYBACK` or `PCM_CAPTURE`. Defaults to `PCM_PLAYBACK`. - **units** (int) - Optional - Specifies the units for the volume. Use constants like `VOLUME_UNITS_PERCENTAGE`, `VOLUME_UNITS_RAW`, or `VOLUME_UNITS_DB`. Defaults to `VOLUME_UNITS_PERCENTAGE`. ### Response #### Success Response (200) - **volumes** (list[int]) - A list of current volume settings for each channel. ### Response Example ```json { "volumes": [80, 80] } ``` ## Mixer.setvolume(volume: int, pcmtype: int = PCM_PLAYBACK, units: int = VOLUME_UNITS_PERCENTAGE, channel: (int | None) = None) ### Description Change the current volume settings for this mixer. ### Method POST ### Endpoint /mixer/volume ### Parameters #### Request Body - **volume** (int) - Required - The desired volume level, its meaning determined by the *units* argument. - **pcmtype** (int) - Optional - Specifies whether to set the volume for playback or capture. Use constants like `PCM_PLAYBACK` or `PCM_CAPTURE`. Defaults to `PCM_PLAYBACK`. - **units** (int) - Optional - Specifies the units for the volume. Use constants like `VOLUME_UNITS_PERCENTAGE`, `VOLUME_UNITS_RAW`, or `VOLUME_UNITS_DB`. Defaults to `VOLUME_UNITS_PERCENTAGE`. - **channel** (int | None) - Optional - If present, the volume is set only for this specific channel. ### Request Example ```json { "volume": 90, "units": 1, "channel": 0 } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. ### Response Example ```json { "message": "Volume set successfully." } ``` ``` -------------------------------- ### List Mixer Controls (Python) Source: https://context7.com/larsimmisch/pyalsaaudio/llms.txt Lists available mixer control names for a given ALSA device using alsaaudio.mixers(). This is similar to the 'amixer' command-line utility. ```python import alsaaudio # List mixers on the default device mixer_controls = alsaaudio.mixers() print("Available mixer controls on default device:") for control in mixer_controls: print(f" '{control}'") # List mixers on a specific card by index mixer_controls_card0 = alsaaudio.mixers(cardindex=0) print("\nMixer controls on card 0:") for control in mixer_controls_card0: print(f" '{control}'") # List mixers on a specific device mixer_controls_hw = alsaaudio.mixers(device='hw:0') print("\nMixer controls on hw:0:") for control in mixer_controls_hw: print(f" '{control}'") ``` -------------------------------- ### List Available PCM Devices (Python) Source: https://context7.com/larsimmisch/pyalsaaudio/llms.txt Lists available PCM device names for audio playback and capture using the alsaaudio.pcms() function. This is analogous to 'aplay -L' and 'arecord -L'. ```python import alsaaudio # List all available playback devices playback_devices = alsaaudio.pcms(alsaaudio.PCM_PLAYBACK) print("Playback devices:") for device in playback_devices: print(f" {device}") # List all available capture devices capture_devices = alsaaudio.pcms(alsaaudio.PCM_CAPTURE) print("\nCapture devices:") for device in capture_devices: print(f" {device}") ``` -------------------------------- ### List Sound Cards (Python) Source: https://context7.com/larsimmisch/pyalsaaudio/llms.txt Retrieves a list of available ALSA sound cards by name and detailed information using alsaaudio.cards() and related functions. Use pcms() for a more practical list of PCM devices. ```python import alsaaudio # List all available sound cards cards = alsaaudio.cards() print("Available sound cards:") for card in cards: print(f" {card}") # Get detailed card information for index in alsaaudio.card_indexes(): name, longname = alsaaudio.card_name(index) print(f"Card {index}: {name} ({longname})") ``` -------------------------------- ### Query PCM Device Configuration Source: https://github.com/larsimmisch/pyalsaaudio/blob/main/doc/libalsaaudio.rst The info method returns a dictionary containing the current configuration of a PCM device. It distinguishes between user-requested values, call-time values, and hardware-derived properties. ```python import alsaaudio # Initialize a PCM object pcm = alsaaudio.PCM(type=alsaaudio.PCM_PLAYBACK, device='default') # Retrieve current configuration config = pcm.info() print(config) ``` -------------------------------- ### Get PCM Type and Mode - Pyalsa Source: https://github.com/larsimmisch/pyalsaaudio/blob/main/doc/libalsaaudio.rst Retrieves the type and mode of a PCM object. The type indicates whether it's for capture or playback, and the mode specifies blocking, non-blocking, or asynchronous operation. ```python pcm_type = PCM.pcmtype() # Returns PCM_CAPTURE or PCM_PLAYBACK pcm_mode = PCM.pcmmode() # Returns PCM_NONBLOCK, PCM_ASYNC, or PCM_NORMAL ``` -------------------------------- ### Handle Enumerated Mixer Controls Source: https://context7.com/larsimmisch/pyalsaaudio/llms.txt Explains how to identify and interact with enumerated mixer controls, such as selecting input sources from a list of available options. ```python import alsaaudio for control_name in alsaaudio.mixers(): try: mixer = alsaaudio.Mixer(control_name) enum_value = mixer.getenum() if enum_value: current, options = enum_value print(f"Control '{control_name}': Current: {current}, Options: {options}") mixer.close() except alsaaudio.ALSAAudioError: pass ``` -------------------------------- ### Play WAV File - Python Script Source: https://github.com/larsimmisch/pyalsaaudio/blob/main/doc/libalsaaudio.rst A Python script ('playwav.py') designed to play a WAV audio file. It accepts the WAV file path as a command-line argument and can optionally take a card name ('-c ') to specify the audio device. ```python python playwav.py ``` -------------------------------- ### Get Mute Status - pyalsaaudio Mixer Source: https://github.com/larsimmisch/pyalsaaudio/blob/main/doc/libalsaaudio.rst Retrieves the current mute status for each channel of an ALSA mixer. Returns a list where 0 indicates not muted and 1 indicates muted. This method requires the mixer to have playback switch capabilities. ```python mixer.getmute() ``` -------------------------------- ### Playback Raw Audio - Python Script Source: https://github.com/larsimmisch/pyalsaaudio/blob/main/doc/libalsaaudio.rst A Python script ('playbacktest.py') for playing back raw audio files previously recorded. It takes the filename as a command-line argument and can optionally specify the audio card. ```python python playbacktest.py ``` -------------------------------- ### PCM Configuration and Utilities Source: https://github.com/larsimmisch/pyalsaaudio/blob/main/doc/libalsaaudio.rst Methods for configuring timestamp modes, managing file descriptors for polling, and closing the PCM device. ```APIDOC ## PCM.set_tstamp_mode([mode: int = PCM_TSTAMP_ENABLE]) ### Description Sets the ALSA timestamp mode on the PCM device. ### Method POST ### Endpoint `/pcm/set_tstamp_mode` ### Parameters #### Query Parameters - **mode** (int) - The timestamp mode. Can be PCM_TSTAMP_NONE or PCM_TSTAMP_ENABLE. Defaults to PCM_TSTAMP_ENABLE. ### Response #### Success Response (200) - **status** (int) - Indicates success or failure of the operation. #### Response Example ```json { "status": 0 } ``` ## PCM.polldescriptors() ### Description Returns a list of file descriptors and event masks that can be used with `select.poll` to wait for changes on the PCM device. ### Method GET ### Endpoint `/pcm/polldescriptors` ### Parameters None ### Response #### Success Response (200) - **descriptors** (list[tuple[int, int]]) - A list of tuples, where each tuple contains a file descriptor and its corresponding event mask. #### Response Example ```json { "descriptors": [ [10, 1], [12, 2] ] } ``` ## PCM.polldescriptors_revents(descriptors: list[tuple[int, int]]) ### Description Processes the descriptor list returned by `polldescriptors` after using it with `select.poll`, and returns a single event mask. ### Method POST ### Endpoint `/pcm/polldescriptors_revents` ### Parameters #### Request Body - **descriptors** (list[tuple[int, int]]) - The list of descriptors returned by `polldescriptors`. ### Response #### Success Response (200) - **event_mask** (int) - A single event mask value indicating the event type. #### Response Example ```json { "event_mask": 1 } ``` ## PCM.close() ### Description Closes the PCM device. For playback streams in normal mode, this function blocks until all pending playback is drained. ### Method POST ### Endpoint `/pcm/close` ### Parameters None ### Response #### Success Response (200) - **status** (int) - Indicates success or failure of the operation. #### Response Example ```json { "status": 0 } ``` ```