### Get Package Version using setup.py Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/api-reference/module-structure.md Demonstrates how to read the package version from the VERSION file during the setup process. ```python version=open("VERSION", encoding="utf8").read(), ``` -------------------------------- ### Install pyrnnoise Source: https://github.com/pengzhendong/pyrnnoise/blob/master/README.md Install the pyrnnoise library using pip. This is the primary method for obtaining the package. ```bash pip install pyrnnoise ``` -------------------------------- ### Full RNNoise Audio Processing Example Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/QUICK-REFERENCE.md This example demonstrates denoising a WAV file, collecting Voice Activity Detection (VAD) probabilities, and includes error handling for file operations. ```python import numpy as np from pyrnnoise import RNNoise from pathlib import Path def process_audio(input_path: str, output_path: str): # Get sample rate from file from audiolab import info rate = info(input_path).rate # Create denoiser denoiser = RNNoise(sample_rate=rate) # Denoise and collect VAD vad_data = [] try: for prob in denoiser.denoise_wav(input_path, output_path): vad_data.append(prob) print(f"✓ Denoised {len(vad_data)} frames") return True except FileNotFoundError: print(f"✗ Input file not found: {input_path}") return False except PermissionError: print(f"✗ Cannot write output: {output_path}") return False except Exception as e: print(f"✗ Error: {e}") return False # Usage process_audio("noisy.wav", "clean.wav") ``` -------------------------------- ### Install Python Package in Development Mode Source: https://github.com/pengzhendong/pyrnnoise/blob/master/README.md Install the Python package in development mode after building the RNNoise library from source. ```bash pip install -e . ``` -------------------------------- ### Build RNNoise Library from Source Source: https://github.com/pengzhendong/pyrnnoise/blob/master/README.md Clone the repository with submodules, build the RNNoise library using CMake, and install it. ```bash # Clone with submodules git submodule update --init # Build RNNoise library cmake -B pyrnnoise/build -DCMAKE_BUILD_TYPE=Release cmake --build pyrnnoise/build --target install ``` -------------------------------- ### Console Script Entry Point Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/api-reference/module-structure.md Defines the 'denoise' command-line script available after installation. ```python entry_points={ "console_scripts": ["denoise = pyrnnoise.cli:main"] } ``` -------------------------------- ### Get Package Version using pkg_resources Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/api-reference/module-structure.md Shows how to access the installed package version using the pkg_resources library. ```python import pkg_resources version = pkg_resources.get_distribution("pyrnnoise").version ``` -------------------------------- ### RNNoise State Management Example Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/configuration.md Demonstrates the lifecycle of denoising states within an RNNoise instance, including creation, usage, and reset behavior with partial frames. ```python from pyrnnoise import RNNoise denoiser = RNNoise(sample_rate=48000) # States not yet created print(denoiser.denoise_states) # None # Process frame - states created on demand for prob, denoised in denoiser.denoise_chunk(audio): pass # States now exist print(type(denoiser.denoise_states)) # list # Process partial frame for prob, denoised in denoiser.denoise_chunk(final_chunk, partial=True): pass # States reset to None after partial=True print(denoiser.denoise_states) # None (after processing) ``` -------------------------------- ### Build and Install rnnoise Library Source: https://github.com/pengzhendong/pyrnnoise/blob/master/CMakeLists.txt Builds the rnnoise library as a shared object. Installs the library to a destination directory within the pyrnnoise subdirectory of the current source directory. ```cmake add_library(rnnoise SHARED ${RNNOISE_SOURCES}) set(PYRNNOISE ${CMAKE_CURRENT_SOURCE_DIR}/pyrnnoise) install(TARGETS rnnoise LIBRARY DESTINATION ${PYRNNOISE} RUNTIME DESTINATION ${PYRNNOISE} ) ``` -------------------------------- ### Verify Pyrnnoise Library Installation Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/errors.md Checks if the pyrnnoise library is installed and accessible by printing key constants like FRAME_SIZE and SAMPLE_RATE. This is a fundamental step in debugging to ensure the library is correctly set up. ```python import pyrnnoise.rnnoise as rn print(f"FRAME_SIZE: {rn.FRAME_SIZE}") print(f"SAMPLE_RATE: {rn.SAMPLE_RATE}") print("Library loaded successfully") ``` -------------------------------- ### Denoise WAV File Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/00-START-HERE.md Use this snippet to denoise a WAV file. Ensure you have the pyrnnoise library installed and specify the sample rate of your audio. ```python from pyrnnoise import RNNoise RNNoise(sample_rate=48000).denoise_wav("noisy.wav", "clean.wav") ``` -------------------------------- ### Console Progress Bar Example Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/api-reference/cli.md Illustrates the progress bar displayed during audio denoising. The progress bar shows the percentage of frames processed, the number of frames completed out of the total, and the processing speed. ```text Denoising: 100%|████████████████| 1234/1234 [00:05<00:00, 234.56frames/s] ``` -------------------------------- ### Batch Process Audio Chunks Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/usage-patterns.md Process large audio files in large chunks to minimize overhead and improve throughput. This example processes audio in 10-second chunks. ```python from pyrnnoise import RNNoise import numpy as np denoiser = RNNoise(sample_rate=48000) # Process in 10-second chunks (better throughput) chunk_size = 480000 # 10 seconds at 48 kHz for start in range(0, len(audio), chunk_size): end = min(start + chunk_size, len(audio)) chunk = audio[start:end] is_final = (end >= len(audio)) for prob, denoised in denoiser.denoise_chunk(chunk, partial=is_final): output.write(denoised) ``` -------------------------------- ### Process Stereo Audio Frame Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/QUICK-REFERENCE.md Example of denoising a stereo audio frame using the denoise_frame method. The output includes speech probabilities and the denoised audio. ```python # Stereo processing stereo_frame = np.random.randint(-32768, 32767, (2, 480), dtype=np.int16) probs, denoised = denoiser.denoise_frame(stereo_frame) # probs: array of shape (2,) with probability per channel # denoised: array of shape (2, 480) ``` -------------------------------- ### Frame Processing Example Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/api-reference/cli.md Explains frame processing for a specific sample rate. The number of frames is calculated based on the total samples and the typical frame size. ```text For a 48 kHz file with 480,000 samples, the progress bar shows 1000 frames. ``` -------------------------------- ### Typical Import and Usage Scenario Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/api-reference/module-structure.md Demonstrates how to import the RNNoise class, initialize a denoiser instance, and process audio frames. The denoiser's native state is automatically cleaned up upon garbage collection. ```python # User code from pyrnnoise import RNNoise import numpy as np # Create denoiser (initializes RNNoise instance) denoiser = RNNoise(sample_rate=48000) # Process audio audio = np.random.randint(-32768, 32767, (480,), dtype=np.int16) speech_prob, denoised = denoiser.denoise_frame(audio) # Denoiser is garbage collected, native state cleaned up del denoiser ``` -------------------------------- ### CLI Entry Point Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/api-reference/module-structure.md The `denoise` command-line interface for processing WAV files. ```APIDOC ## CLI Entry Point ### `main(in_wav: str, out_wav: str, plot: bool) -> None` Main function for the `denoise` command-line script. Processes an input WAV file (`in_wav`) and saves the denoised output to `out_wav`. Optionally generates a plot if `plot` is True. ``` -------------------------------- ### Project and Version Configuration Source: https://github.com/pengzhendong/pyrnnoise/blob/master/CMakeLists.txt Sets the minimum CMake version and project name. Defines build options for runtime CPU detection and building a demo binary. ```cmake cmake_minimum_required(VERSION 3.14) project("RnNoise" LANGUAGES C) option(RTCD "Enable x86 run-time CPU detection" OFF) option(BUILD_BIN "Build rnnoise_demo binary" OFF) ``` -------------------------------- ### Handle Different Sample Rates Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/QUICK-REFERENCE.md Demonstrates initializing the RNNoise denoiser with different sample rates. Processing at the native 48 kHz is optimal, while other rates will incur resampling overhead. ```python # Best: process at native 48 kHz (no resampling) denoiser_48k = RNNoise(sample_rate=48000) # Also works: will resample (adds ~5-10% overhead) denoiser_16k = RNNoise(sample_rate=16000) denoiser_44k = RNNoise(sample_rate=44100) ``` -------------------------------- ### Create Output Directory Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/api-reference/cli.md Use this command to create the output directory if it is missing. The -p flag ensures that parent directories are also created if they do not exist. ```bash mkdir -p /path/to/output denoiser input.wav /path/to/output/output.wav ``` -------------------------------- ### Process Stereo Frame with Shape Mismatch Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/errors.md Example demonstrating an AssertionError due to a shape mismatch between the number of states (stereo) and the frame's channel count. ```python import numpy as np from pyrnnoise.rnnoise import create, process_frame # Two states (stereo) states = [create(), create()] # But three channels in frame frame = np.random.randint(-32768, 32767, (3, 480), dtype=np.int16) try: denoised, probs = process_frame(states, frame) except AssertionError: print("State count mismatch") ``` -------------------------------- ### Basic File Denoising with Command-Line Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/00-START-HERE.md Use the pyrnnoise command-line interface to denoise an audio file. The --plot flag can be used to visualize the process. ```bash denoise noisy.wav clean.wav --plot ``` -------------------------------- ### Process Mono Frame with Unsupported Data Type Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/errors.md Example demonstrating an AssertionError triggered by an unsupported frame data type (uint8) during mono frame processing. ```python import numpy as np from pyrnnoise.rnnoise import process_mono_frame, create state = create() frame = np.array([100, 200, 300], dtype=np.uint8) # Unsupported try: denoised, prob = process_mono_frame(state, frame) except AssertionError: print("Unsupported data type") ``` -------------------------------- ### Instantiate and Denoise with RNNoise Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/README.md Create an RNNoise denoiser instance and use it to process WAV files or individual audio frames. Ensure the sample rate is correctly specified. ```python from pyrnnoise import RNNoise # Create denoiser denoiser = RNNoise(sample_rate=48000) # Denoise file for speech_prob in denoiser.denoise_wav("input.wav", "output.wav"): pass # Or process frames speech_prob, denoised = denoiser.denoise_frame(frame) # Or stream chunks for speech_prob, denoised in denoiser.denoise_chunk(audio): process(denoised) ``` -------------------------------- ### Basic Command-Line Denoising Source: https://github.com/pengzhendong/pyrnnoise/blob/master/README.md Use the command-line interface to denoise an input WAV file and save the output to another WAV file. ```bash denoise input.wav output.wav ``` -------------------------------- ### Extract speech segments Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/00-START-HERE.md This example shows how to extract speech segments from audio data by identifying frames with high speech probability. It requires post-processing to find contiguous speech segments. ```python speech_frames = [prob > 0.5 for prob, _ in denoiser.denoise_chunk(audio)] # Find contiguous True segments ``` -------------------------------- ### Get RNNoise Frame Size Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/api-reference/rnnoise-module.md Retrieves the frame size in samples required by the RNNoise engine from the native library. This value determines the fixed size of audio frames processed by RNNoise. ```python FRAME_SIZE = lib.rnnoise_get_frame_size() ``` -------------------------------- ### Initialize RNNoise with Different Sample Rates Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/QUICK-REFERENCE.md Instantiate the RNNoise model with various sample rates. Note that some rates may require resampling. ```python RNNoise(sample_rate=8000) # Telephony (resamples) RNNoise(sample_rate=16000) # Speech recognition (resamples) RNNoise(sample_rate=44100) # CD audio (resamples) RNNoise(sample_rate=48000) # Professional (native, fast!) RNNoise(sample_rate=96000) # Hi-res (resamples) ``` -------------------------------- ### RNNoise: Denoise Mono and Stereo Frames Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/api-reference/rnnoise-class.md Demonstrates how to initialize the RNNoise denoiser and process both mono and stereo audio frames. Ensure the frame size matches RNNoise.FRAME_SIZE. ```python import numpy as np from pyrnnoise import RNNoise denoiser = RNNoise(sample_rate=48000) # Mono audio mono_frame = np.random.randint(-32768, 32767, (480,), dtype=np.int16) speech_prob, denoised = denoiser.denoise_frame(mono_frame) print(f"Speech probability: {speech_prob[0]:.2f}") # Stereo audio stereo_frame = np.random.randint(-32768, 32767, (2, 480), dtype=np.int16) speech_probs, denoised = denoiser.denoise_frame(stereo_frame) print(f"Left channel speech prob: {speech_probs[0, 0]:.2f}") print(f"Right channel speech prob: {speech_probs[1, 0]:.2f}") ``` -------------------------------- ### Extract Speech Segments using VAD Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/README.md Utilize the Voice Activity Detection (VAD) output from `denoise_chunk` to identify speech segments. This example finds contiguous segments where speech probability exceeds a threshold. ```python vad = [prob > 0.5 for prob, _ in denoiser.denoise_chunk(audio)] # Find contiguous True segments ``` -------------------------------- ### Automatic Input Audio Format Detection and Processing Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/configuration.md Shows how to use the audiolab library to detect properties of an audio file and then initialize the RNNoise denoiser with the detected sample rate. The denoiser can then process the audio file. ```python from pyrnnoise import RNNoise from audiolab import info # Auto-detect properties file_info = info("input.wav") print(f"Sample rate: {file_info.rate}") print(f"Channels: {file_info.channels}") print(f"Duration: {file_info.duration:.2f}s") # Create denoiser with detected sample rate denoiser = RNNoise(sample_rate=file_info.rate) denoiser.denoise_wav("input.wav", "output.wav") ``` -------------------------------- ### Initialize RNNoise Denoiser Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/api-reference/rnnoise-class.md Instantiate the RNNoise class with the sample rate of your audio. The class handles internal resampling if the provided sample rate is not 48 kHz. ```python from pyrnnoise import RNNoise # Create denoiser for 48 kHz audio denoiser = RNNoise(sample_rate=48000) # Create denoiser for 16 kHz audio (will resample internally) denoiser_16k = RNNoise(sample_rate=16000) ``` -------------------------------- ### Process Multiple WAV Files Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/QUICK-REFERENCE.md Recursively finds all WAV files in an 'audio' directory and processes them using the denoiser, saving the cleaned output to an 'output' directory. Uses pathlib for path manipulation. ```python from pathlib import Path for wav_file in Path("audio").glob("*.wav"): output = Path("output") / f"{wav_file.stem}_clean.wav" for _ in denoiser.denoise_wav(str(wav_file), str(output)): pass ``` -------------------------------- ### File Organization Structure Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/INDEX.md Illustrates the directory structure for the PyRNNoise project files. ```text /workspace/home/output/ ├── INDEX.md (this file) ├── OVERVIEW.md ├── types.md ├── configuration.md ├── errors.md ├── usage-patterns.md └── api-reference/ ├── rnnoise-class.md ├── rnnoise-module.md ├── cli.md └── module-structure.md ``` -------------------------------- ### Handle different sample rates Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/00-START-HERE.md This snippet shows how to initialize the RNNoise denoiser with a sample rate determined from an audio file. This ensures compatibility with various audio formats. ```python from audiolab import info rate = info("audio.wav").rate denoiser = RNNoise(sample_rate=rate) ``` -------------------------------- ### Platform-Specific Library Loading Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/configuration.md Illustrates the logic used within the pyrnnoise.rnnoise module to detect the operating system and assign the appropriate RNNoise library filename. This process is automatic and requires no user intervention. ```python # In pyrnnoise.rnnoise module initialization platform = platform.system() if platform == "Darwin": LIBRNNOISE = "librnnoise.dylib" elif platform == "Windows": LIBRNNOISE = "rnnoise.dll" elif platform == "Linux": LIBRNNOISE = "librnnoise.so" ``` -------------------------------- ### Model Download and Extraction Source: https://github.com/pengzhendong/pyrnnoise/blob/master/CMakeLists.txt Reads the model version, constructs the model filename, and downloads the model archive using wget. Extracts the archive using tar. ```cmake file(STRINGS "rnnoise/model_version" VERSION LIMIT_COUNT 1) set(MODEL "rnnoise_data-${VERSION}.tar.gz") execute_process( COMMAND wget -c -N --progress=bar:force https://modelscope.cn/models/pengzhendong/rnnoise/resolve/master/${MODEL} WORKING_DIRECTORY rnnoise ) execute_process(COMMAND tar xvomf ${MODEL} WORKING_DIRECTORY rnnoise) ``` -------------------------------- ### Python API: Basic Denoising Source: https://github.com/pengzhendong/pyrnnoise/blob/master/README.md Initialize the RNNoise denoiser and process an audio file, printing speech probabilities for each frame. ```python from pyrnnoise import RNNoise # Create denoiser instance denoiser = RNNoise(sample_rate=48000) # Process audio file for speech_prob in denoiser.denoise_wav("input.wav", "output.wav"): print(f"Processing frame with speech probability: {speech_prob}") ``` -------------------------------- ### Basic File Denoising with Python Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/00-START-HERE.md Create an RNNoise instance and denoise an audio file. The denoiser processes the audio and saves the cleaned version to a new file. It yields voice activity detection probabilities per frame. ```python from pyrnnoise import RNNoise # Create denoiser denoiser = RNNoise(sample_rate=48000) # Denoise a file for prob in denoiser.denoise_wav("noisy.wav", "clean.wav"): pass ``` -------------------------------- ### Catch OSError for Unsupported OS Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/errors.md Demonstrates how to catch an OSError that occurs if the operating system is not supported by the pyrnnoise library. ```python try: from pyrnnoise.rnnoise import lib except OSError as e: print(f"Unsupported platform: {e}") ``` -------------------------------- ### RNNoise Class Initialization Source: https://github.com/pengzhendong/pyrnnoise/blob/master/README.md Initializes the RNNoise denoiser. The sample rate must match the audio being processed. ```APIDOC ## RNNoise(sample_rate: int) ### Description Initializes the RNNoise denoiser with the specified sample rate. ### Parameters #### Path Parameters - **sample_rate** (int) - Required - The sample rate of the audio to be processed (e.g., 48000). ``` -------------------------------- ### RNNoise: Denoise WAV File Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/api-reference/rnnoise-class.md Illustrates the high-level `denoise_wav` method for denoising an entire WAV file and saving the output. It automatically handles sample rate and channel detection, and yields speech probabilities for progress monitoring. ```python from pyrnnoise import RNNoise denoiser = RNNoise(sample_rate=48000) # Denoise file and collect VAD probabilities speech_probs = [] for prob in denoiser.denoise_wav("noisy.wav", "denoised.wav"): speech_probs.append(prob) print(f"Denoising complete. Processed {len(speech_probs)} frames.") ``` -------------------------------- ### Denoise Chunk Return Values Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/QUICK-REFERENCE.md Illustrates the usage of the `denoise_chunk` method, which yields denoised frames and their speech probabilities for each frame within a given audio chunk. This is suitable for streaming applications. ```python for speech_prob, denoised in denoiser.denoise_chunk(chunk): # Yields (speech_prob, denoised) for each frame pass ``` -------------------------------- ### Recommended Import Pattern Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/api-reference/module-structure.md Import the RNNoise class directly from the top-level package for high-level denoising interface. ```python from pyrnnoise import RNNoise denoiser = RNNoise(sample_rate=48000) ``` -------------------------------- ### Real-Time RNNoise Processing Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/QUICK-REFERENCE.md For lowest latency, process audio one frame at a time using `denoise_frame`. Avoid chunking if minimal latency is critical. ```python denoiser = RNNoise(sample_rate=48000) # Process one frame at a time (10 ms latency) speech_prob, denoised = denoiser.denoise_frame(frame) # Rather than chunking for speech_prob, denoised in denoiser.denoise_chunk(frame): pass ``` -------------------------------- ### CLI Error: Missing argument 'OUT_WAV' Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/errors.md This error indicates that the output WAV file argument was not provided. Always supply both input and output file paths. ```bash $ denoise input.wav Error: Missing argument 'OUT_WAV'. ``` -------------------------------- ### Project Directory Structure Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/README.md This snippet shows the directory layout of the pyrnoise project, indicating the location of various documentation files and source code organization. ```tree output/ ├── README.md (this file) ├── INDEX.md (navigation guide) ├── OVERVIEW.md (project overview) ├── QUICK-REFERENCE.md (fast lookup) ├── types.md (type definitions) ├── configuration.md (config & constants) ├── errors.md (error reference) ├── usage-patterns.md (code examples) └── api-reference/ ├── rnnoise-class.md (RNNoise class) ├── rnnoise-module.md (low-level bindings) ├── cli.md (command-line tool) └── module-structure.md (package organization) ``` -------------------------------- ### Catching Click Exceptions in Python Scripts Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/errors.md Demonstrates how to use Click's testing utilities to invoke the CLI and catch specific exceptions like MissingParameter or BadParameter. This is useful for automated testing and error handling within Python applications. ```python from click.testing import CliRunner from pyrnnoise.cli import main runner = CliRunner() result = runner.invoke(main, ['missing.wav', 'output.wav']) if result.exit_code != 0: print(f"CLI error: {result.output}") ``` -------------------------------- ### Debugging RNNoise Library and Audio Files Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/QUICK-REFERENCE.md Check if the RNNoise library is loaded and print its configuration. Also, inspect audio file information using the audiolab library. ```python # Check library loaded from pyrnnoise.rnnoise import lib, FRAME_SIZE, SAMPLE_RATE print(f"Loaded RNNoise") print(f"Frame size: {FRAME_SIZE} samples") print(f"Sample rate: {SAMPLE_RATE} Hz") # Check audio file from audiolab import info file_info = info("audio.wav") print(f"File sample rate: {file_info.rate}") print(f"File duration: {file_info.duration:.2f}s") ``` -------------------------------- ### Configure RNNoise with Different Sample Rates Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/configuration.md Instantiate the RNNoise class with the desired sample rate for input audio. The library handles resampling internally if the provided rate is not 48000 Hz. ```python from pyrnnoise import RNNoise # 48 kHz (native rate, no resampling) denoiser_48k = RNNoise(sample_rate=48000) # 16 kHz (will be resampled internally) denoiser_16k = RNNoise(sample_rate=16000) # 44.1 kHz (common for CD audio) denoiser_44k = RNNoise(sample_rate=44100) # 8 kHz (telephony) denoiser_8k = RNNoise(sample_rate=8000) ``` -------------------------------- ### Include Directories and Source Files Source: https://github.com/pengzhendong/pyrnnoise/blob/master/CMakeLists.txt Specifies include directories for the project and defines the list of C source files for the rnnoise library. ```cmake include_directories(rnnoise/include rnnoise/src) set(RNNOISE_SOURCES rnnoise/src/celt_lpc.c rnnoise/src/denoise.c rnnoise/src/kiss_fft.c rnnoise/src/parse_lpcnet_weights.c rnnoise/src/pitch.c rnnoise/src/rnn.c rnnoise/src/rnnoise_data.c rnnoise/src/rnnoise_tables.c rnnoise/src/nnet.c rnnoise/src/nnet_default.c ) ``` -------------------------------- ### Accessing PyRNNoise Library Constants Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/configuration.md Demonstrates how to import and use the fixed constants defined within the pyrnnoise.rnnoise module. These constants represent fundamental properties of the RNNoise library. ```python from pyrnnoise.rnnoise import FRAME_SIZE, SAMPLE_RATE, FRAME_SIZE_MS print(f"Frame size: {FRAME_SIZE} samples") print(f"At {SAMPLE_RATE} Hz = {FRAME_SIZE_MS} ms") print(f"Duration: {FRAME_SIZE / SAMPLE_RATE:.3f} seconds") ``` -------------------------------- ### Low-Level API Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/QUICK-REFERENCE.md The low-level API allows direct control over the RNNoise state, enabling manual creation, processing, and destruction of the denoiser state. ```APIDOC ## Low-Level API ### Description Provides direct access to RNNoise state management and frame processing. ### Functions - **create() -> object** Creates and initializes an RNNoise state object. - **process_frame(state: object, frame: np.ndarray) -> Tuple[np.ndarray, np.ndarray]** Processes a single audio frame using the provided RNNoise state. Returns the denoised frame and speech probability. - **destroy(state: object)** Destroys and cleans up the RNNoise state object. ``` -------------------------------- ### File-based Denoising (Python API) Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/00-START-HERE.md Instantiate the RNNoise denoiser and process an input WAV file to an output WAV file. The loop iterates through voice activity detection probabilities. ```python denoiser = RNNoise(sample_rate=48000) for prob in denoiser.denoise_wav("input.wav", "output.wav"): pass ``` -------------------------------- ### Low-Level RNNoise API Usage Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/QUICK-REFERENCE.md Demonstrates the low-level API for RNNoise, including creating a state, processing a frame, and destroying the state. This is useful for manual control over the denoising process. ```python from pyrnnoise.rnnoise import create, destroy, process_frame state = create() denoiser = RNNoise(sample_rate=48000) # Assuming denoiser is initialized elsewhere or this is a simplified example frame = np.random.randint(-32768, 32767, (480,), dtype=np.int16) # Assuming frame is defined denoiser, speech_prob = process_frame(state, frame) destroy(state) ``` -------------------------------- ### Initialize RNNoise at Native Sample Rate Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/usage-patterns.md Initialize the RNNoise denoiser at the audio's native sample rate (preferably 48 kHz) to avoid resampling overhead. If the native rate is different, RNNoise will resample, which incurs a small performance cost. ```python from pyrnnoise import RNNoise from pyrnnoise.rnnoise import SAMPLE_RATE # Best: Process audio natively at 48 kHz (no resampling) denoiser = RNNoise(sample_rate=48000) # Also fine: Audio will be resampled (adds ~5-10% overhead) denoiser = RNNoise(sample_rate=16000) ``` -------------------------------- ### Import RNNoise Class Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/QUICK-REFERENCE.md Import the RNNoise class from the pyrnnoise library. ```python from pyrnnoise import RNNoise ``` -------------------------------- ### Convert Other Audio Formats to Int16 Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/usage-patterns.md Demonstrates converting 24-bit audio (represented as 32-bit integers) to int16 format before denoising. This is useful for handling audio data from various sources. ```python from pyrnnoise import RNNoise import numpy as np denoiser = RNNoise(sample_rate=48000) # 24-bit audio as 32-bit int (range 0 to 2^24) audio_24bit = np.array([1000000, 2000000, 3000000], dtype=np.int32) # Convert to int16 audio_int16 = (audio_24bit >> 8).astype(np.int16) speech_prob, denoised = denoiser.denoise_frame(audio_int16) ``` -------------------------------- ### CLI Denoising Command Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/README.md Use the command-line interface to denoise WAV files. The `--plot` option can be added for VAD visualization. ```bash denoise input.wav output.wav # Basic denoise input.wav output.wav --plot # With VAD visualization ``` -------------------------------- ### Low-Level Bindings Import Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/api-reference/module-structure.md For advanced use cases, import functions and constants from the low-level pyrnnoise.rnnoise module. ```python from pyrnnoise.rnnoise import ( create, destroy, process_frame, process_mono_frame, FRAME_SIZE, SAMPLE_RATE, FRAME_SIZE_MS, DTYPE, ) state = create() # ... use state ... destroy(state) ``` -------------------------------- ### Process streaming audio Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/00-START-HERE.md This snippet demonstrates how to process audio data in chunks for real-time streaming applications. It yields speech probability and denoised audio for each chunk. ```python for speech_prob, denoised in denoiser.denoise_chunk(audio_data): send_to_speaker(denoised) ``` -------------------------------- ### Output Resampling Graph Configuration Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/configuration.md Configure the output resampling graph to convert RNNoise output back to the original sample rate. This graph ensures compatibility with the original audio format. ```python out_graph = Graph( rate=48000, # RNNoise output rate dtype=np.int16, # RNNoise output dtype channels=num_channels, # Preserved from input filters=[aformat(np.int16, self.sample_rate)], # Convert to original sample rate ) ``` -------------------------------- ### Denoise WAV Return Values and File Output Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/QUICK-REFERENCE.md Describes the `denoise_wav` method, which processes an entire WAV file. It yields speech probabilities for each frame and saves the denoised audio to a specified output path. This method is ideal for batch processing of audio files. ```python for speech_prob in denoiser.denoise_wav(in_path, out_path): # Yields speech_prob for each frame # Also saves denoised audio to out_path pass ``` -------------------------------- ### Handle Different Sample Rates with RNNoise Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/usage-patterns.md Handle audio at various sample rates by specifying the correct rate when creating the RNNoise denoiser. The actual sample rate can be detected using audiolab.info. ```python from pyrnnoise import RNNoise from audiolab import info # Detect actual sample rate audio_info = info("my_audio.wav") rate = audio_info.rate # Create denoiser with correct rate denoiser = RNNoise(sample_rate=rate) for speech_prob in denoiser.denoise_wav("my_audio.wav", "denoised_audio.wav"): pass ``` -------------------------------- ### Convert Unsupported Audio Codec to PCM WAV Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/errors.md Use ffmpeg to convert WAV files with unsupported codecs (e.g., compressed formats) to a PCM WAV format. ```bash ffmpeg -i compressed.wav -acodec pcm_s16le output.wav ``` -------------------------------- ### Basic Denoising Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/configuration.md Use this command for basic denoising without VAD visualization. The `--no-plot` flag is implied. ```bash # Basic denoising, no plot denoise input.wav output.wav ``` -------------------------------- ### Basic RNNoise Testing Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/QUICK-REFERENCE.md Perform basic tests on the RNNoise denoiser by processing silence and noise. Asserts low speech probability for silence. ```python from pyrnnoise import RNNoise from pyrnnoise.rnnoise import FRAME_SIZE import numpy as np denoiser = RNNoise(sample_rate=48000) # Test with silence silence = np.zeros((FRAME_SIZE,), dtype=np.int16) prob, _ = denoiser.denoise_frame(silence) assert prob < 0.5 # Should have low speech probability # Test with noise noise = np.random.randint(-32768, 32767, (FRAME_SIZE,), dtype=np.int16) prob, _ = denoiser.denoise_frame(noise) # prob will be higher but still somewhat low ``` -------------------------------- ### Handle Different Sample Rates Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/README.md Automatically detect the sample rate of an input audio file using `audiolab.info` and initialize the RNNoise denoiser with the detected rate. This ensures compatibility with various audio formats. ```python from audiolab import info rate = info("audio.wav").rate denoiser = RNNoise(sample_rate=rate) ``` -------------------------------- ### Catch FileNotFoundError for Input WAV Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/errors.md Use a try-except block to catch FileNotFoundError when the input WAV file does not exist for `denoise_wav()`. ```python from pyrnnoise import RNNoise denoiser = RNNoise(sample_rate=48000) try: for prob in denoiser.denoise_wav("nonexistent.wav", "output.wav"): pass except FileNotFoundError: print("Input file not found") ``` -------------------------------- ### Input Resampling Graph Configuration Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/configuration.md Configure the input resampling graph when the input sample rate differs from 48 kHz. This graph handles the initial conversion to the RNNoise expected format. ```python in_graph = Graph( rate=self.sample_rate, # Input sample rate dtype=input_dtype, # Detected from first frame channels=num_channels, # Detected from first frame filters=[aformat(np.int16, 48000)], # Convert to int16 at 48 kHz frame_size=480, # RNNoise frame size ) ``` -------------------------------- ### Direct Low-Level RNNoise Usage Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/api-reference/rnnoise-module.md Use this pattern for advanced scenarios requiring direct state management. It involves manually creating, processing, and destroying RNNoise states for each audio channel. ```python from pyrnnoise.rnnoise import create, destroy, process_frame, FRAME_SIZE import numpy as np # Create a state for each channel states = [create(), create()] # Process frames frame = np.random.randint(-32768, 32767, (2, FRAME_SIZE), dtype=np.int16) denoiser, speech_probs = process_frame(states, frame) # Clean up for state in states: destroy(state) ``` -------------------------------- ### Thread-Safe RNNoise Initialization Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/QUICK-REFERENCE.md Each thread must have its own RNNoise instance to ensure thread safety. Do not share a denoiser instance across multiple threads. ```python # NOT thread-safe: each thread needs its own instance from pyrnnoise import RNNoise # In thread 1 denoiser1 = RNNoise(sample_rate=48000) # In thread 2 denoiser2 = RNNoise(sample_rate=48000) # Never share denoiser between threads! ``` -------------------------------- ### Denoise Frame Return Values Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/QUICK-REFERENCE.md Explains the return values of the `denoise_frame` method. It returns the speech probability for each channel and the denoised audio frame in Int16 format. ```python speech_prob, denoised = denoiser.denoise_frame(frame) # speech_prob: array of float 0-1 (one per channel) # denoised: array same shape as input, int16 ``` -------------------------------- ### Use Context Manager for Automatic RNNoise Cleanup Source: https://github.com/pengzhendong/pyrnnoise/blob/master/_autodocs/usage-patterns.md Implement a context manager to ensure RNNoise resources are automatically cleaned up upon exiting the 'with' block. This pattern simplifies resource management and prevents leaks. ```python from pyrnnoise import RNNoise from contextlib import contextmanager @contextmanager def denoiser_context(sample_rate): denoiser = RNNoise(sample_rate=sample_rate) try: yield denoiser finally: del denoiser # Usage with denoiser_context(48000) as denoiser: for prob, denoised in denoiser.denoise_chunk(audio): process(denoised) # Automatically cleaned up here ```