简体   繁体   中英

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM