Jaoa
Jaoa

Reputation: 95

Using Python to run a sox command for converting wav files

I would like to process .wav files in Python. Particularly, I would like to perform following operation

sox input.wav -c 1 -r 16000 output.wav

in every .wav file in my folder. My code is below:

#!/usr/bin/python
# encoding=utf8
# -*- encoding: utf -*-

import glob
import subprocess

segments= []
for filename in glob.glob('*.wav'):
        new_filename = "converted_" + filename
        subprocess.call("sox" + filename + "-c 1 -r 16000" + new_filename, shell=True)

However, it is not working as expected that it's not calling my command.

Upvotes: 2

Views: 2781

Answers (1)

finefoot
finefoot

Reputation: 11232

When you write

subprocess.call("sox" + filename + "-c 1 -r 16000" + new_filename, shell=True)

what's actually going to be executed for an exemplary TEST.WAV file looks like this:

soxTEST.WAV-c 1 -r 16000converted_TEST.WAV

So you're missing the spaces in between. A nice solution using Python's f-strings (Formatted string literals) would be something like this:

subprocess.call(f"sox {filename} -c 1 -r 16000 {new_filename}", shell=True)

However, I'd recommend switching over to subprocess.run and disregarding the shell=True flag:

subprocess.run(["sox", filename, "-c 1", "-r 16000", new_filename])

More information also at the docs https://docs.python.org/3/library/subprocess.html

Note: Read the Security Considerations section before using shell=True.

Upvotes: 2

Related Questions