### Example Usage of Device Information Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/types.md Demonstrates how to retrieve and print specific details from a device information dictionary obtained using PyAudio. Ensure PyAudio is installed and initialized. ```python import pyaudio p = pyaudio.PyAudio() device_info = p.get_device_info_by_index(0) print(f"Device: {device_info['name']}") print(f"Max input channels: {device_info['maxInputChannels']}") print(f"Max output channels: {device_info['maxOutputChannels']}") print(f"Default sample rate: {device_info['defaultSampleRate']}") print(f"Input latency (low): {device_info['defaultLowInputLatency']}") print(f"Output latency (high): {device_info['defaultHighOutputLatency']}") p.terminate() ``` -------------------------------- ### Install PyAudio with Pip Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/README.md Use pip to install PyAudio. Pre-compiled wheels are available. ```bash pip install pyaudio ``` -------------------------------- ### PyAudio Stream with Callback and Time Info Usage Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/types.md An example of setting up a PyAudio stream with a callback function that prints the current stream time and output DAC time. Ensure PyAudio is installed and audio devices are available. ```python import pyaudio def callback(in_data, frame_count, time_info, status): current = time_info['current_time'] output_dac = time_info['output_buffer_dac_time'] print(f"Current time: {current}, Output DAC time: {output_dac}") return (in_data, pyaudio.paContinue) p = pyaudio.PyAudio() stream = p.open(format=pyaudio.paInt16, channels=1, rate=44100, input=True, output=True, stream_callback=callback) import time while stream.is_active(): time.sleep(0.1) stream.close() p.terminate() ``` -------------------------------- ### Install PyAudio on Windows Source: https://github.com/cristifati/pyaudio/blob/master/README.md Installs PyAudio with precompiled PortAudio on Windows using pip. ```shell python -m pip install pyaudio ``` -------------------------------- ### Install PyAudio on macOS Source: https://github.com/cristifati/pyaudio/blob/master/README.md Installs PortAudio via Homebrew, then installs PyAudio using pip on macOS. ```shell brew install portaudio pip install pyaudio ``` -------------------------------- ### Install PyAudio on Linux Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/README.md On Debian/Ubuntu systems, install the python3-pyaudio package or use pip. ```bash sudo apt install python3-pyaudio # Or via pip pip install pyaudio ``` -------------------------------- ### Install PyAudio on GNU/Linux Source: https://github.com/cristifati/pyaudio/blob/master/README.md Installs PyAudio using the apt package manager on Debian-based systems. ```shell sudo apt install python3-pyaudio ``` -------------------------------- ### Start Audio Stream Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/exports.md Starts the audio stream, enabling audio input or output. This should be called after the stream has been opened and configured. ```python PyAudio.Stream.start_stream() -> None ``` -------------------------------- ### Play Audio File with PyAudio Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/README.md Basic usage example demonstrating how to initialize PyAudio, open a wave file, and play its contents through an output stream. ```python import pyaudio import wave # Initialize p = pyaudio.PyAudio() # Open a wave file with wave.open('audio.wav', 'rb') as wf: # Create output stream stream = p.open( format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=wf.getframerate(), output=True ) # Play the file CHUNK = 1024 while True: data = wf.readframes(CHUNK) if not data: break stream.write(data) # Cleanup stream.close() p.terminate() ``` -------------------------------- ### Get Default Host API Info Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/types.md Retrieves and prints information about the default host API, including its name, device count, and default input/output devices. Ensure PyAudio is installed and initialized. ```python import pyaudio p = pyaudio.PyAudio() api_info = p.get_default_host_api_info() print(f"Default Host API: {api_info['name']}") print(f"Devices: {api_info['deviceCount']}") print(f"Default input device: {api_info['defaultInputDevice']}") print(f"Default output device: {api_info['defaultOutputDevice']}") p.terminate() ``` -------------------------------- ### PyAudio.Stream.start_stream Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/exports.md Starts the audio stream, enabling audio input or output. ```APIDOC ## PyAudio.Stream.start_stream ### Description Start the stream. ### Method `start_stream()` ### Returns `None` ``` -------------------------------- ### Get Sample Size in PyAudio Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/api-reference/pyaudio.md Demonstrates how to get the byte size of audio samples for different formats like 16-bit integer and 32-bit float using `pyaudio.get_sample_size`. ```python import pyaudio # Get the size of a 16-bit integer sample size = pyaudio.get_sample_size(pyaudio.paInt16) print(f"paInt16 sample size: {size} bytes") # Output: 2 # Get the size of a 32-bit float sample size = pyaudio.get_sample_size(pyaudio.paFloat32) print(f"paFloat32 sample size: {size} bytes") # Output: 4 ``` -------------------------------- ### List All Audio Devices in Python Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/usage-patterns.md Iterates through all available audio devices and prints their details, including input/output channels and default sample rate. Ensure PyAudio is installed. ```python import pyaudio def list_devices(): p = pyaudio.PyAudio() print("=" * 60) print("Available Audio Devices") print("=" * 60) for i in range(p.get_device_count()): info = p.get_device_info_by_index(i) print(f"\nDevice {i}: {info['name']}") print(f" Input Channels: {info['maxInputChannels']}") print(f" Output Channels: {info['maxOutputChannels']}") print(f" Sample Rate: {info['defaultSampleRate']}") print("\n" + "=" * 60) p.terminate() list_devices() ``` -------------------------------- ### Start an Audio Stream Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/api-reference/stream.md Use start_stream() to begin audio playback or recording if the stream is currently stopped. This method has no effect if the stream is already running. ```python import pyaudio p = pyaudio.PyAudio() stream = p.open(format=pyaudio.paInt16, channels=1, rate=44100, output=True, start=False) # Stream is not yet running; start it stream.start_stream() stream.close() p.terminate() ``` -------------------------------- ### Calculate Audio Buffer Sizes with PyAudio Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/types.md Demonstrates how to calculate the number of bytes per sample, bytes per frame, and total bytes for a given number of frames using PyAudio. Ensure PyAudio is installed and imported. ```python import pyaudio format = pyaudio.paInt16 channels = 2 rate = 44100 frame_count = 1024 p = pyaudio.PyAudio() bytes_per_sample = p.get_sample_size(format) bytes_per_frame = bytes_per_sample * channels total_bytes = bytes_per_frame * frame_count print(f"Bytes per sample: {bytes_per_sample}") print(f"Bytes per frame: {bytes_per_frame}") print(f"Total bytes for {frame_count} frames: {total_bytes}") p.terminate() ``` -------------------------------- ### Get Host API Count and Info - PyAudio Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/api-reference/pyaudio-class.md Iterates through all available host APIs, printing their names and device counts. Requires PyAudio to be imported and initialized. ```python import pyaudio p = pyaudio.PyAudio() api_count = p.get_host_api_count() print(f"Available host APIs: {api_count}") for i in range(api_count): api_info = p.get_host_api_info_by_index(i) print(f" {api_info['name']} (devices: {api_info['deviceCount']})") p.terminate() ``` -------------------------------- ### Get Format from Width Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/exports.md Obtain a sample format constant from a given sample byte width. Optionally specify if the format should be unsigned. ```python pyaudio.get_format_from_width(width: int, unsigned: bool = True) -> int ``` -------------------------------- ### Get Host API Info by Type Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/exports.md Fetches information about a host audio API given its type constant (e.g., `paMME`, `paCoreAudio`). This allows querying specific API details. ```python PyAudio.get_host_api_info_by_type(host_api_type: int) -> dict ``` -------------------------------- ### Full-Duplex Callback Example Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/api-reference/stream.md Demonstrates a full-duplex stream using a callback function that echoes input data as output. This is useful for applications requiring simultaneous input and output processing. The stream is active for a limited duration. ```python import pyaudio import time p = pyaudio.PyAudio() def callback(in_data, frame_count, time_info, status): # Echo: return input data as output return (in_data, pyaudio.paContinue) stream = p.open(format=pyaudio.paInt16, channels=1, rate=44100, input=True, output=True, stream_callback=callback) start = time.time() while stream.is_active() and (time.time() - start) < 5: time.sleep(0.1) stream.close() p.terminate() ``` -------------------------------- ### Dynamic Linking PortAudio on Linux/macOS Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/architecture.md Use this command to dynamically link the PortAudio library when building the PyAudio extension on Linux or macOS. Ensure PortAudio is installed on your system. ```bash gcc -shared src/pyaudio/*.c -lportaudio -o _portaudio.so ``` -------------------------------- ### Get Default Host API Info - PyAudio Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/api-reference/pyaudio-class.md Retrieves and prints the name and device count of the default host API. Ensure PyAudio is imported and initialized before use. ```python import pyaudio p = pyaudio.PyAudio() api_info = p.get_default_host_api_info() print(f"Default API: {api_info['name']}") print(f"Devices: {api_info['deviceCount']}") p.terminate() ``` -------------------------------- ### Get Default Host API Info Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/exports.md Retrieves information about the system's default host audio API. This includes its type, name, and the number of devices associated with it. ```python PyAudio.get_default_host_api_info() -> dict ``` -------------------------------- ### Example Function Export in C Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/architecture.md Demonstrates how C functions are exported to Python using a method definition table. This is typically found in the main C file of the extension module. ```c static PyMethodDef exported_functions[] = { {"initialize", PyAudio_Initialize, METH_VARARGS, "Initializes PortAudio"}, {"open", PyAudio_Open, METH_VARARGS | METH_KEYWORDS, "Opens a stream"}, // ... more functions ... }; ``` -------------------------------- ### Get PyAudio Format from Width Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/api-reference/pyaudio.md Shows how to obtain PortAudio sample format constants from byte widths using `pyaudio.get_format_from_width`. It covers 16-bit, 32-bit, and 8-bit unsigned/signed formats. ```python import pyaudio # Get format for 16-bit (2-byte) samples fmt = pyaudio.get_format_from_width(2) print(fmt == pyaudio.paInt16) # True # Get format for 32-bit (4-byte) float samples fmt = pyaudio.get_format_from_width(4) print(fmt == pyaudio.paFloat32) # True # Get unsigned 8-bit format fmt = pyaudio.get_format_from_width(1, unsigned=True) print(fmt == pyaudio.paUInt8) # True # Get signed 8-bit format fmt = pyaudio.get_format_from_width(1, unsigned=False) print(fmt == pyaudio.paInt8) # True ``` -------------------------------- ### Get Default Input and Output Devices in Python Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/usage-patterns.md Retrieves and prints the names and indices of the default audio input and output devices. Handles cases where no default device is found. ```python import pyaudio def show_default_devices(): p = pyaudio.PyAudio() try: input_device = p.get_default_input_device_info() print(f"Default Input: {input_device['name']} (index {input_device['index']})") except IOError: print("No default input device") try: output_device = p.get_default_output_device_info() print(f"Default Output: {output_device['name']} (index {output_device['index']})") except IOError: print("No default output device") p.terminate() show_default_devices() ``` -------------------------------- ### CoreAudio Channel Mapping Configuration Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/api-reference/mac-core-stream-info.md Sets up an audio stream with a custom channel map, directing logical channels to specific physical CoreAudio channels. This example maps two logical channels to physical channels 0 and 2. ```python import pyaudio if hasattr(pyaudio._portaudio, 'paMacCoreStreamInfo'): p = pyaudio.PyAudio() # Map 2 channels to specific CoreAudio channels stream_info = pyaudio.PaMacCoreStreamInfo( channel_map=(0, 2) # Map logical channels 0,1 to physical channels 0,2 ) stream = p.open(format=pyaudio.paInt16, channels=2, rate=44100, output=True, output_host_api_specific_stream_info=stream_info) stream.close() p.terminate() ``` -------------------------------- ### Get Host API Info by Index - PyAudio Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/api-reference/pyaudio-class.md Lists all host APIs by iterating through their indices and printing their names. This method is useful for enumerating available host APIs. PyAudio must be initialized. ```python import pyaudio p = pyaudio.PyAudio() for i in range(p.get_host_api_count()): api_info = p.get_host_api_info_by_index(i) print(f"{i}: {api_info['name']}") p.terminate() ``` -------------------------------- ### Get Default Output Device Info Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/api-reference/pyaudio-class.md Retrieve the information for the system's default audio output device. Includes error handling for scenarios where no output device is found. ```python import pyaudio p = pyaudio.PyAudio() try: output_device = p.get_default_output_device_info() print(f"Default output device: {output_device['name']}") except IOError: print("No output device available") p.terminate() ``` -------------------------------- ### __init__ Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/exports.md Initializes PyAudio and the PortAudio system. This is the constructor for the PyAudio class. ```APIDOC ## __init__ ### Description Initializes PyAudio and PortAudio system. ### Method Constructor ### Parameters None ### Response - **PyAudio** (PyAudio) - An instance of the PyAudio class. ``` -------------------------------- ### Basic CoreAudio Stream Configuration Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/api-reference/mac-core-stream-info.md Demonstrates how to open an audio stream with default CoreAudio settings, using paMacCorePlayNice. Ensure PyAudio and the necessary CoreAudio extensions are available. ```python import pyaudio if hasattr(pyaudio._portaudio, 'paMacCoreStreamInfo'): p = pyaudio.PyAudio() # Use default settings (paMacCorePlayNice) stream_info = pyaudio.PaMacCoreStreamInfo() stream = p.open(format=pyaudio.paInt16, channels=2, rate=44100, output=True, output_host_api_specific_stream_info=stream_info) stream.close() p.terminate() ``` -------------------------------- ### Initialize PyAudio Instance Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/api-reference/pyaudio-class.md Initializes the PyAudio instance and PortAudio system resources. Ensure to terminate the instance when done to release resources. ```python import pyaudio p = pyaudio.PyAudio() try: # Use PyAudio pass finally: p.terminate() ``` -------------------------------- ### Get Host API Info by Type - PyAudio Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/api-reference/pyaudio-class.md Fetches and prints the device count for a specific host API type, such as ALSA. Includes error handling for unavailable types. Requires PyAudio and the relevant host API type constant. ```python import pyaudio p = pyaudio.PyAudio() try: alsa_info = p.get_host_api_info_by_type(pyaudio.paALSA) print(f"ALSA devices: {alsa_info['deviceCount']}") except IOError: print("ALSA not available on this system") p.terminate() ``` -------------------------------- ### Initialize and Terminate PyAudio (Standard) Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/usage-patterns.md Use this standard pattern for initializing PyAudio and ensuring termination to release resources, especially within a try-finally block. ```python import pyaudio # Initialize PortAudio p = pyaudio.PyAudio() try: # Use PyAudio pass finally: # Always terminate to release resources p.terminate() ``` -------------------------------- ### Initialize and Terminate PyAudio (Context Manager) Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/usage-patterns.md Implement a context manager wrapper for PyAudio to automatically handle initialization and termination, simplifying resource management. ```python import pyaudio from contextlib import contextmanager @contextmanager def audio_manager(): p = pyaudio.PyAudio() try: yield p finally: p.terminate() with audio_manager() as p: # Use p pass ``` -------------------------------- ### Get Flags (Deprecated) Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/exports.md Deprecated method to get CoreAudio flags. Use the `flags` property instead. ```python PaMacCoreStreamInfo.get_flags() -> int ``` -------------------------------- ### Get Channel Map (Deprecated) Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/exports.md Deprecated method to get the channel map. Use the `channel_map` property instead. ```python PaMacCoreStreamInfo.get_channel_map() -> tuple | None ``` -------------------------------- ### PyAudio Constructor Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/api-reference/pyaudio-class.md Initializes the PyAudio instance and PortAudio system resources. Returns a new PyAudio instance with PortAudio initialized. Raises IOError if PortAudio initialization fails. ```APIDOC ## PyAudio() ### Description Initializes the PyAudio instance and PortAudio system resources. ### Parameters None ### Returns PyAudio - A new PyAudio instance with PortAudio initialized. ### Raises IOError - if PortAudio initialization fails. The exception is a tuple of `(error_code, error_message)`. ### Example ```python import pyaudio p = pyaudio.PyAudio() try: # Use PyAudio pass finally: p.terminate() ``` ``` -------------------------------- ### List Available Host APIs on Linux Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/configuration.md Check and list the available audio host APIs and their associated device counts on a Linux system. This helps in understanding the audio backend options supported by PyAudio. ```python import pyaudio p = pyaudio.PyAudio() for i in range(p.get_host_api_count()): api_info = p.get_host_api_info_by_index(i) print(f"{api_info['name']}: {api_info['deviceCount']} devices") p.terminate() ``` -------------------------------- ### Get Current Stream Time Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/api-reference/stream.md Get the current time of the audio stream in seconds. For callback streams, this advances at the callback rate; for blocking streams, it reflects processed frames. ```python import pyaudio p = pyaudio.PyAudio() stream = p.open(format=pyaudio.paInt16, channels=1, rate=44100, output=True) current_time = stream.get_time() print(f"Stream time: {current_time} seconds") stream.close() p.terminate() ``` -------------------------------- ### PyAudio.Stream.get_time Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/exports.md Gets the current time of the audio stream in seconds. ```APIDOC ## PyAudio.Stream.get_time ### Description Get current stream time in seconds. ### Method `get_time()` ### Returns `float` - The current stream time in seconds. ``` -------------------------------- ### open Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/exports.md Opens a new audio stream with the specified parameters. This method allows for detailed configuration of audio input and output streams. ```APIDOC ## open ### Description Open a new audio stream. ### Method `PyAudio.open()` ### Parameters - **rate** (int) - The sample rate in Hz. - **channels** (int) - The number of audio channels. - **format** (int) - The sample format (e.g., `paInt16`). - **input** (bool) - Whether the stream is for input (default: False). - **output** (bool) - Whether the stream is for output (default: False). - **input_device_index** (int | None) - The index of the input device (default: None). - **output_device_index** (int | None) - The index of the output device (default: None). - **frames_per_buffer** (int) - The number of frames per buffer (default: `paFramesPerBufferUnspecified`). - **start** (bool) - Whether to start the stream immediately (default: True). - **input_host_api_specific_stream_info** (object | None) - Host API specific stream info for input (default: None). - **output_host_api_specific_stream_info** (object | None) - Host API specific stream info for output (default: None). - **stream_callback** (Callable | None) - A callback function to be called for each audio buffer (default: None). ### Response - **Stream** (PyAudio.Stream) - An object representing the opened audio stream. ``` -------------------------------- ### Get PortAudio Version (Integer) Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/exports.md Retrieve the PortAudio library version as an integer. ```python pyaudio.get_portaudio_version() -> int ``` -------------------------------- ### Get PortAudio Version (Text) Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/exports.md Retrieve the PortAudio library version as a human-readable string. ```python pyaudio.get_portaudio_version_text() -> str ``` -------------------------------- ### Get PortAudio Version Number Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/api-reference/pyaudio.md Retrieves the PortAudio library version as an integer using `pyaudio.get_portaudio_version`. ```python import pyaudio version = pyaudio.get_portaudio_version() print(f"PortAudio version: {version}") # e.g., 19 for v19 ``` -------------------------------- ### Stream.start_stream() Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/api-reference/stream.md Starts the audio stream if it is currently stopped. If the stream is already running, this method has no effect. ```APIDOC ## Stream.start_stream() ### Description Starts the stream if it is stopped. Does nothing if the stream is already running. ### Method `Stream.start_stream()` ### Parameters None ### Returns None ### Example ```python import pyaudio p = pyaudio.PyAudio() stream = p.open(format=pyaudio.paInt16, channels=1, rate=44100, output=True, start=False) # Stream is not yet running; start it stream.start_stream() stream.close() p.terminate() ``` ``` -------------------------------- ### Get PortAudio Version Text Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/api-reference/pyaudio.md Fetches the PortAudio library version as a human-readable string using `pyaudio.get_portaudio_version_text`. ```python import pyaudio version_text = pyaudio.get_portaudio_version_text() print(f"PortAudio version text: {version_text}") # e.g., "PortAudio V19.7.0-devel" ``` -------------------------------- ### Selecting Audio Format in PyAudio Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/configuration.md Demonstrates three methods for selecting an audio sample format in PyAudio. Method 1 uses a direct constant, Method 2 converts from byte width, and Method 3 checks the sample size for a given format. ```python import pyaudio p = pyaudio.PyAudio() # Method 1: Use constant directly fmt = pyaudio.paInt16 # Method 2: Convert from byte width fmt = p.get_format_from_width(2) # 2 bytes = 16-bit # Method 3: Check sample size size = p.get_sample_size(pyaudio.paInt16) # Returns 2 p.terminate() ``` -------------------------------- ### PyAudio.open() Method Signature Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/configuration.md This is the full signature for the `PyAudio.open()` method, outlining all available parameters for configuring an audio stream. Required parameters include `rate`, `channels`, and `format`. Optional parameters control input/output devices, buffer size, and stream callbacks. ```python PyAudio.open( rate: int, # REQUIRED channels: int, # REQUIRED format: int, # REQUIRED input: bool = False, # OPTIONAL output: bool = False, # OPTIONAL input_device_index: int | None = None, # OPTIONAL output_device_index: int | None = None, # OPTIONAL frames_per_buffer: int = paFramesPerBufferUnspecified, # OPTIONAL start: bool = True, # OPTIONAL input_host_api_specific_stream_info: object | None = None, # OPTIONAL output_host_api_specific_stream_info: object | None = None, # OPTIONAL stream_callback: Callable | None = None # OPTIONAL ) -> PyAudio.Stream ``` -------------------------------- ### Get Write Available Frames Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/exports.md Returns the number of audio frames that can be written to the output stream without blocking. ```python PyAudio.Stream.get_write_available() -> int ``` -------------------------------- ### Initialize PyAudio Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/exports.md Initializes the PyAudio library and the PortAudio system. This should be called before any other PyAudio operations. ```python PyAudio() ``` -------------------------------- ### Get Sample Size Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/exports.md Determine the byte size of a single audio sample based on the provided format constant. ```python pyaudio.get_sample_size(format: int) -> int ``` -------------------------------- ### Get Current Stream Time Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/exports.md Returns the current time of the audio stream in seconds. This can be useful for synchronizing audio events. ```python PyAudio.Stream.get_time() -> float ``` -------------------------------- ### Get Input Latency Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/exports.md Retrieves the input latency of the audio stream in seconds. This indicates the delay between when audio is captured and when it is available. ```python PyAudio.Stream.get_input_latency() -> float ``` -------------------------------- ### Configure Playback Stream with Device Defaults Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/configuration.md Opens a default output stream using device-specific settings for format, channels, and sample rate. Ensures compatibility with the selected audio device. ```python import pyaudio p = pyaudio.PyAudio() # Get default output device device_info = p.get_default_output_device_info() # Use device defaults stream = p.open( format=pyaudio.paInt16, # Safe default channels=min(2, device_info['maxOutputChannels']), rate=int(device_info['defaultSampleRate']), output=True, frames_per_buffer=1024 ) stream.close() p.terminate() ``` -------------------------------- ### Get Read Available Frames Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/exports.md Returns the number of audio frames currently available to be read from the input stream without blocking. ```python PyAudio.Stream.get_read_available() -> int ``` -------------------------------- ### Configure Recording Stream with Device Defaults Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/configuration.md Opens a default input stream using device-specific settings for format, channels, and sample rate. Suitable for general audio recording. ```python import pyaudio p = pyaudio.PyAudio() # Get default input device device_info = p.get_default_input_device_info() # Use device defaults stream = p.open( format=pyaudio.paInt16, channels=min(1, device_info['maxInputChannels']), rate=int(device_info['defaultSampleRate']), input=True, frames_per_buffer=1024 ) stream.close() p.terminate() ``` -------------------------------- ### Get Output Latency Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/exports.md Retrieves the output latency of the audio stream in seconds. This indicates the delay between when audio data is sent and when it is played. ```python PyAudio.Stream.get_output_latency() -> float ``` -------------------------------- ### Resource Management with Context Manager Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/README.md An alternative pattern for resource management using a context manager. This approach simplifies resource cleanup by automatically handling the termination of the PyAudio instance. ```python from contextlib import contextmanager import pyaudio @contextmanager def audio_session(): p = pyaudio.PyAudio() try: yield p finally: p.terminate() with audio_session() as p: stream = p.open(...) ``` -------------------------------- ### Initialize PyAudio Stream Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/exports.md Initializes a new audio stream. This method should not be called directly; use `PyAudio.open()` instead. It configures parameters like sample rate, channels, format, and device indices. ```python PyAudio.Stream.__init__( PA_manager: PyAudio, rate: int, channels: int, format: int, input: bool = False, output: bool = False, input_device_index: int | None = None, output_device_index: int | None = None, frames_per_buffer: int = paFramesPerBufferUnspecified, start: bool = True, input_host_api_specific_stream_info: object | None = None, output_host_api_specific_stream_info: object | None = None, stream_callback: Callable | None = None ) ``` -------------------------------- ### Get Input Stream Latency Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/api-reference/stream.md Retrieve the input latency for a stream in seconds. This is important for applications sensitive to audio delay during input. ```python import pyaudio p = pyaudio.PyAudio() stream = p.open(format=pyaudio.paInt16, channels=1, rate=44100, input=True) latency = stream.get_input_latency() print(f"Input latency: {latency} seconds") stream.close() p.terminate() ``` -------------------------------- ### Checking Device Availability and Format Support Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/errors.md Before opening an audio stream, verify device existence using `get_device_info_by_index` and check format compatibility with `is_format_supported`. This prevents `IOError` exceptions and ensures the chosen format and channels are valid for the selected device. ```python import pyaudio p = pyaudio.PyAudio() device_index = 0 try: # Check device exists info = p.get_device_info_by_index(device_index) # Check format support supported = p.is_format_supported( rate=44100, output_device=device_index, output_channels=info['maxOutputChannels'], output_format=pyaudio.paInt16 ) if supported: stream = p.open(format=pyaudio.paInt16, channels=info['maxOutputChannels'], rate=44100, output=True, output_device_index=device_index) else: print("Format not supported") except IOError as e: print(f"Error: {e.args[1]}") p.terminate() ``` -------------------------------- ### Get CPU Load Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/exports.md Reports the current CPU load utilized by the audio stream. Returns 0.0 if the stream is operating in blocking mode. ```python PyAudio.Stream.get_cpu_load() -> float ``` -------------------------------- ### Get Format from Width Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/exports.md Determines the PyAudio sample format constant based on the byte width of the samples. An optional `unsigned` parameter can be specified. ```python PyAudio.get_format_from_width(width: int, unsigned: bool = True) -> int ``` -------------------------------- ### Graceful Stream Opening with Fallback Configurations Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/usage-patterns.md Attempts to open an audio stream with a list of preferred configurations, falling back to alternatives if the preferred ones fail. Useful for ensuring compatibility across different audio devices. ```python import pyaudio def open_stream_with_fallback(): p = pyaudio.PyAudio() # Try configurations in order of preference configs = [ {'rate': 48000, 'channels': 2, 'format': pyaudio.paFloat32}, {'rate': 44100, 'channels': 2, 'format': pyaudio.paInt32}, {'rate': 44100, 'channels': 2, 'format': pyaudio.paInt16}, {'rate': 44100, 'channels': 1, 'format': pyaudio.paInt16}, {'rate': 22050, 'channels': 1, 'format': pyaudio.paInt16}, ] stream = None for config in configs: try: stream = p.open(output=True, **config) print(f"Successfully opened stream with {config}") break except IOError as e: print(f"Failed with {config}: {e.args[1]}") if stream is None: print("Could not open any stream") p.terminate() return None return stream, p stream, p = open_stream_with_fallback() if stream: stream.close() p.terminate() ``` -------------------------------- ### Python to C Tuple Creation and Access Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/architecture.md Shows how to pack Python objects into a C tuple and retrieve an item by its index using PyTuple_Pack and PyTuple_GetItem. ```c // Tuple PyObject *tuple = PyTuple_Pack(2, obj1, obj2); PyObject *item = PyTuple_GetItem(tuple, 0); ``` -------------------------------- ### Get Output Stream Latency Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/api-reference/stream.md Obtain the output latency for a stream in seconds. This value is crucial for synchronizing audio output with other media or devices. ```python import pyaudio p = pyaudio.PyAudio() stream = p.open(format=pyaudio.paInt16, channels=1, rate=44100, output=True) latency = stream.get_output_latency() print(f"Output latency: {latency} seconds") stream.close() p.terminate() ``` -------------------------------- ### Get Device Count Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/exports.md Returns the total number of audio devices available on the system. This can be used to iterate through devices or check for the presence of audio hardware. ```python PyAudio.get_device_count() -> int ``` -------------------------------- ### Print System Audio Information with PyAudio Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/usage-patterns.md Retrieve and display detailed information about the system's audio hardware, including PortAudio version, host APIs, and available devices. This requires initializing PyAudio. ```python import pyaudio def print_system_info(): p = pyaudio.PyAudio() print(f"PortAudio Version: {pyaudio.get_portaudio_version_text()}") print(f"Host APIs: {p.get_host_api_count()}") print(f"Devices: {p.get_device_count()}") print("\n" + "=" * 60) print("Host APIs") print("=" * 60) for i in range(p.get_host_api_count()): api_info = p.get_host_api_info_by_index(i) print(f"\n{api_info['name']}:") print(f" Index: {api_info['index']}") print(f" Devices: {api_info['deviceCount']}") print(f" Default Input: {api_info['defaultInputDevice']}") print(f" Default Output: {api_info['defaultOutputDevice']}") p.terminate() print_system_info() ``` -------------------------------- ### Open an Audio Stream Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/api-reference/stream.md Use PyAudio.open() to create an audio stream. Do not instantiate PyAudio.Stream directly. This method configures the stream's rate, channels, format, and I/O direction. ```python stream = pyaudio.PyAudio().open( rate: int, channels: int, format: int, input: bool = False, output: bool = False, ... ) -> PyAudio.Stream ``` -------------------------------- ### Python to C Dictionary Creation and Access Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/architecture.md Demonstrates creating a new Python dictionary in C, setting a string key-value pair, and retrieving a value using PyDict_New, PyDict_SetItemString, and PyDict_GetItemString. ```c // Dictionary PyObject *dict = PyDict_New(); PyDict_SetItemString(dict, "key", value_obj); PyObject *val = PyDict_GetItemString(dict, "key"); ``` -------------------------------- ### Get Default Input Device Info Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/exports.md Fetches the information for the system's default audio input device. This is typically the microphone that applications will use by default. ```python PyAudio.get_default_input_device_info() -> dict ``` -------------------------------- ### Handle Unsupported Sample Format in PyAudio Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/errors.md Demonstrates catching an IOError when trying to open a stream with a sample format that the audio device does not support. This can occur if the device lacks support for formats like paFloat32. ```python import pyaudio p = pyaudio.PyAudio() try: # Device may not support paFloat32 stream = p.open(format=pyaudio.paFloat32, channels=2, rate=44100, output=True) except IOError as e: error_code, error_msg = e.args print(f"Format not supported: {e}") p.terminate() ``` -------------------------------- ### Basic Output (Playback) Configuration Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/configuration.md Configure a PyAudio stream for basic audio playback. Sets format to 16-bit signed, stereo channels, and CD-quality sample rate. ```python import pyaudio p = pyaudio.PyAudio() stream = p.open( format=pyaudio.paInt16, # 16-bit signed channels=2, # Stereo rate=44100, # CD quality output=True ) # Use stream for playback stream.close() p.terminate() ``` -------------------------------- ### Basic Input (Recording) Configuration Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/configuration.md Configure a PyAudio stream for basic audio recording. Sets format to 16-bit signed, mono channel, and CD-quality sample rate. ```python import pyaudio p = pyaudio.PyAudio() stream = p.open( format=pyaudio.paInt16, channels=1, # Mono rate=44100, input=True ) # Use stream for recording stream.close() p.terminate() ``` -------------------------------- ### Get Sample Size from Format Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/api-reference/pyaudio-class.md Use `get_sample_size()` to determine the byte size of a single audio sample for a given PortAudio format. This is useful for buffer calculations. ```python import pyaudio p = pyaudio.PyAudio() size = p.get_sample_size(pyaudio.paInt16) print(f"paInt16 sample size: {size} bytes") # 2 p.terminate() ``` -------------------------------- ### PaMacCoreStreamInfo Constructor Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/api-reference/mac-core-stream-info.md Initializes a macOS CoreAudio stream info configuration object with optional flags and channel mapping. ```APIDOC ## PaMacCoreStreamInfo Constructor ### Description Initializes a macOS CoreAudio stream info configuration object. ### Signature ```python PaMacCoreStreamInfo(flags: int | None = None, channel_map: tuple | None = None) ``` ### Parameters #### Parameters - **flags** (int or None) - Optional - OR'ed combination of PaMacCore flags - **channel_map** (tuple or None) - Optional - Channel mapping tuple of integers ### Returns PaMacCoreStreamInfo — A new CoreAudio stream info object. ### Raises ValueError — if channel_map is not a tuple or contains non-integer elements. SystemError — if memory allocation fails. ### Example ```python import pyaudio if hasattr(pyaudio._portaudio, 'paMacCoreStreamInfo'): p = pyaudio.PyAudio() # Create with default settings stream_info = pyaudio.PaMacCoreStreamInfo() # Create with specific flags stream_info = pyaudio.PaMacCoreStreamInfo( flags=pyaudio.PaMacCoreStreamInfo.paMacCorePlayNice ) # Use in stream opening stream = p.open(format=pyaudio.paInt16, channels=2, rate=44100, output=True, output_host_api_specific_stream_info=stream_info) stream.close() p.terminate() ``` ``` -------------------------------- ### Get Default Output Device Info Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/exports.md Fetches the information for the system's default audio output device. This is typically the speakers or headphones that applications will use by default. ```python PyAudio.get_default_output_device_info() -> dict ``` -------------------------------- ### CoreAudio Combined Flags and Channel Mapping Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/api-reference/mac-core-stream-info.md Demonstrates combining multiple CoreAudio stream flags, such as paMacCorePro and paMacCoreChangeDeviceParameters, along with a channel map. This allows for fine-grained control over stream behavior and routing. ```python import pyaudio if hasattr(pyaudio._portaudio, 'paMacCoreStreamInfo'): p = pyaudio.PyAudio() # Combine multiple flags using bitwise OR flags = (pyaudio.PaMacCoreStreamInfo.paMacCorePro | pyaudio.PaMacCoreStreamInfo.paMacCoreChangeDeviceParameters) stream_info = pyaudio.PaMacCoreStreamInfo( flags=flags, channel_map=(0, 1) ) stream = p.open(format=pyaudio.paInt16, channels=2, rate=44100, output=True, output_host_api_specific_stream_info=stream_info) stream.close() p.terminate() ``` -------------------------------- ### Create Audio Stream with Specific Format Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/api-reference/pyaudio.md Use `pyaudio.paInt16` to specify a 16-bit signed integer format when opening an audio stream. Ensure PyAudio is imported before use. ```python import pyaudio p = pyaudio.PyAudio() # Create a stream that expects 16-bit signed integer samples stream = p.open(format=pyaudio.paInt16, channels=2, rate=44100, output=True) ``` -------------------------------- ### Get Total Audio Device Count Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/api-reference/pyaudio-class.md Use this to determine the number of audio input and output devices available on the system. It's often a prerequisite for iterating through devices. ```python import pyaudio p = pyaudio.PyAudio() num_devices = p.get_device_count() print(f"Available audio devices: {num_devices}") for i in range(num_devices): info = p.get_device_info_by_index(i) print(f"Device {i}: {info['name']}") p.terminate() ``` -------------------------------- ### Handle paHostApiNotFound Error in PyAudio Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/errors.md Catch `IOError` when requesting a host API type that is not available or not compiled into the PortAudio build. For example, ASIO might not be available on all systems. ```python import pyaudio p = pyaudio.PyAudio() try: # ASIO may not be available on all systems api_info = p.get_host_api_info_by_type(pyaudio.paASIO) except IOError as e: error_code, error_msg = e.args print(f"Host API not found: {e}") p.terminate() ``` -------------------------------- ### Accessing PaMacCoreStreamInfo Flags Source: https://github.com/cristifati/pyaudio/blob/master/_autodocs/api-reference/mac-core-stream-info.md Demonstrates how to initialize PaMacCoreStreamInfo with specific flags and access the flags property. Requires the paMacCoreStreamInfo constant to be available. ```python import pyaudio if hasattr(pyaudio._portaudio, 'paMacCoreStreamInfo'): stream_info = pyaudio.PaMacCoreStreamInfo( flags=pyaudio.PaMacCoreStreamInfo.paMacCorePlayNice ) print(f"Flags: {stream_info.flags}") ```