Python SoX Wrapper
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
- breaking Python 3.7 and earlier are no longer supported as of `sox` version 1.5.0. Users on these older Python versions must upgrade to Python 3.8+ or pin `sox` to an earlier version (e.g., `<1.5.0`).
- gotcha The `sox` Python library is a wrapper for the *external* SoX command-line tool. You MUST have the SoX executable installed and accessible in your system's PATH for this library to function. The library itself does not bundle the SoX executable.
- gotcha Prior to version 1.5.0, `sox` primarily expected string paths for file operations. While string paths still work, version 1.5.0 and later added explicit support for `pathlib.Path` objects. Mixed usage or assuming `Path` objects on older versions may lead to errors.
- gotcha Errors during SoX command execution (e.g., malformed input, unsupported effects, missing codecs) are wrapped in `sox.SoxError`. It's good practice to catch this specific exception to handle issues gracefully, rather than relying on generic `Exception` catches.
Install
-
pip install sox
Imports
- sox
import sox
- Transformer
from sox import Transformer
Quickstart
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)