Python SoX Wrapper

1.5.0 · active · verified Sun Apr 12

The `sox` library provides a Python wrapper around the SoX (Sound eXchange) command-line tool, enabling Python programs to perform audio processing tasks such as format conversion, effects application, and mixing. The current version is 1.5.0, released in late 2023, and it generally follows a release cadence tied to significant feature additions or Python version support updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `sox.Transformer` to apply effects and convert an audio file. It includes checks for the external SoX command-line tool and generates a dummy input file if one isn't present to make the example runnable.

import sox
import os
import subprocess

input_file = "input_audio.wav"
output_file = "output_processed.wav"

# --- Pre-requisite Check: SoX command-line tool ---
try:
    subprocess.run(["sox", "--version"], check=True, capture_output=True)
except (subprocess.CalledProcessError, FileNotFoundError):
    print("WARNING: The SoX command-line tool is not found. Please install it first.")
    print("  (e.g., `sudo apt-get install sox` on Debian/Ubuntu, `brew install sox` on macOS)")
    # Exit or provide placeholder if SoX isn't installed. For quickstart, we'll print and continue
    # to show the Python API, but expect actual failure if SoX isn't present.

# --- Generate a dummy input file if it doesn't exist ---
if not os.path.exists(input_file):
    print(f"Generating dummy '{input_file}' for the example...")
    try:
        # Use SoX itself to create a 1-second sine wave file
        subprocess.run(["sox", "-n", input_file, "synth", "1", "sine", "440"], check=True)
        print(f"Successfully generated '{input_file}'.")
    except (subprocess.CalledProcessError, FileNotFoundError):
        print(f"Failed to generate '{input_file}'. Please ensure SoX is installed and accessible in PATH, or provide your own '{input_file}'.")

# --- SoX Transformation Example ---
if os.path.exists(input_file):
    # Initialize a Transformer object
    tfm = sox.Transformer()

    # Apply some audio effects
    tfm.trim(0.1, 0.9) # Trim from 0.1s to 0.9s
    tfm.set_output_format(rate=16000, channels=1) # Resample to 16kHz mono
    tfm.compand(attack=0.3, decay=0.8, soft_knee=6, threshold=-40, ratio=5) # Apply dynamic range compression

    # Build the output file. The 'build' method executes the SoX command.
    try:
        tfm.build(input_file, output_file)
        print(f"Transformation complete! Output saved to '{output_file}'.")
        print(f"Original file size: {os.path.getsize(input_file)} bytes")
        print(f"Processed file size: {os.path.getsize(output_file)} bytes")
    except sox.SoxError as e:
        print(f"Error during SoX transformation: {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
else:
    print("Skipping transformation: Input file not found.")

# --- Clean up (optional) ---
# if os.path.exists(output_file):
#     os.remove(output_file)
# if os.path.exists(input_file):
#     os.remove(input_file)

view raw JSON →