{"id":4766,"library":"sox","title":"Python SoX Wrapper","description":"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.","status":"active","version":"1.5.0","language":"en","source_language":"en","source_url":"https://github.com/rabitt/pysox","tags":["audio","sound","signal processing","wrapper","sox"],"install":[{"cmd":"pip install sox","lang":"bash","label":"Install `sox` Python package"}],"dependencies":[],"imports":[{"note":"While the GitHub repository is named 'pysox', the installed Python package and its top-level import name is `sox`.","wrong":"import pysox","symbol":"sox","correct":"import sox"},{"note":"Common classes like Transformer are directly available under the top-level 'sox' module, not nested under a 'transform' submodule.","wrong":"from sox.transform import Transformer","symbol":"Transformer","correct":"from sox import Transformer"}],"quickstart":{"code":"import sox\nimport os\nimport subprocess\n\ninput_file = \"input_audio.wav\"\noutput_file = \"output_processed.wav\"\n\n# --- Pre-requisite Check: SoX command-line tool ---\ntry:\n    subprocess.run([\"sox\", \"--version\"], check=True, capture_output=True)\nexcept (subprocess.CalledProcessError, FileNotFoundError):\n    print(\"WARNING: The SoX command-line tool is not found. Please install it first.\")\n    print(\"  (e.g., `sudo apt-get install sox` on Debian/Ubuntu, `brew install sox` on macOS)\")\n    # Exit or provide placeholder if SoX isn't installed. For quickstart, we'll print and continue\n    # to show the Python API, but expect actual failure if SoX isn't present.\n\n# --- Generate a dummy input file if it doesn't exist ---\nif not os.path.exists(input_file):\n    print(f\"Generating dummy '{input_file}' for the example...\")\n    try:\n        # Use SoX itself to create a 1-second sine wave file\n        subprocess.run([\"sox\", \"-n\", input_file, \"synth\", \"1\", \"sine\", \"440\"], check=True)\n        print(f\"Successfully generated '{input_file}'.\")\n    except (subprocess.CalledProcessError, FileNotFoundError):\n        print(f\"Failed to generate '{input_file}'. Please ensure SoX is installed and accessible in PATH, or provide your own '{input_file}'.\")\n\n# --- SoX Transformation Example ---\nif os.path.exists(input_file):\n    # Initialize a Transformer object\n    tfm = sox.Transformer()\n\n    # Apply some audio effects\n    tfm.trim(0.1, 0.9) # Trim from 0.1s to 0.9s\n    tfm.set_output_format(rate=16000, channels=1) # Resample to 16kHz mono\n    tfm.compand(attack=0.3, decay=0.8, soft_knee=6, threshold=-40, ratio=5) # Apply dynamic range compression\n\n    # Build the output file. The 'build' method executes the SoX command.\n    try:\n        tfm.build(input_file, output_file)\n        print(f\"Transformation complete! Output saved to '{output_file}'.\")\n        print(f\"Original file size: {os.path.getsize(input_file)} bytes\")\n        print(f\"Processed file size: {os.path.getsize(output_file)} bytes\")\n    except sox.SoxError as e:\n        print(f\"Error during SoX transformation: {e}\")\n    except Exception as e:\n        print(f\"An unexpected error occurred: {e}\")\nelse:\n    print(\"Skipping transformation: Input file not found.\")\n\n# --- Clean up (optional) ---\n# if os.path.exists(output_file):\n#     os.remove(output_file)\n# if os.path.exists(input_file):\n#     os.remove(input_file)\n","lang":"python","description":"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."},"warnings":[{"fix":"Upgrade Python to 3.8 or newer, or specify `sox<1.5.0` in your dependencies.","message":"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`).","severity":"breaking","affected_versions":">=1.5.0"},{"fix":"Install the SoX command-line tool via your system's package manager (e.g., `sudo apt-get install sox` on Debian/Ubuntu, `brew install sox` on macOS, or download from the SoX homepage for Windows).","message":"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.","severity":"gotcha","affected_versions":"All versions"},{"fix":"For `sox<1.5.0`, always convert `pathlib.Path` objects to strings using `str(path_obj)` before passing them to `sox` functions. For `sox>=1.5.0`, `pathlib.Path` objects can be used directly.","message":"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.","severity":"gotcha","affected_versions":"<1.5.0"},{"fix":"Wrap calls to `tfm.build()` (and similar methods that execute SoX) in a `try...except sox.SoxError:` block to specifically handle SoX-related failures.","message":"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.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-12T00:00:00.000Z","next_check":"2026-07-11T00:00:00.000Z"}