使用 Python 到 运行 用于转换 wav 文件的 sox 命令
Using Python to run a sox command for converting wav files
我想处理 Python 中的 .wav
个文件。特别是,我想执行以下操作
sox input.wav -c 1 -r 16000 output.wav
在我文件夹中的每个 .wav
文件中。我的代码如下:
#!/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)
但是,它没有按预期工作,它没有调用我的命令。
写的时候
subprocess.call("sox" + filename + "-c 1 -r 16000" + new_filename, shell=True)
示例性 TEST.WAV
文件实际要执行的内容如下所示:
soxTEST.WAV-c 1 -r 16000converted_TEST.WAV
所以你错过了中间的空格。使用 Python 的 f-strings (Formatted string literals) 的一个很好的解决方案是这样的:
subprocess.call(f"sox {filename} -c 1 -r 16000 {new_filename}", shell=True)
但是,我建议切换到 subprocess.run
并忽略 shell=True
标志:
subprocess.run(["sox", filename, "-c 1", "-r 16000", new_filename])
有关文档的更多信息 https://docs.python.org/3/library/subprocess.html
Note: Read the Security Considerations section before using shell=True
.
我想处理 Python 中的 .wav
个文件。特别是,我想执行以下操作
sox input.wav -c 1 -r 16000 output.wav
在我文件夹中的每个 .wav
文件中。我的代码如下:
#!/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)
但是,它没有按预期工作,它没有调用我的命令。
写的时候
subprocess.call("sox" + filename + "-c 1 -r 16000" + new_filename, shell=True)
示例性 TEST.WAV
文件实际要执行的内容如下所示:
soxTEST.WAV-c 1 -r 16000converted_TEST.WAV
所以你错过了中间的空格。使用 Python 的 f-strings (Formatted string literals) 的一个很好的解决方案是这样的:
subprocess.call(f"sox {filename} -c 1 -r 16000 {new_filename}", shell=True)
但是,我建议切换到 subprocess.run
并忽略 shell=True
标志:
subprocess.run(["sox", filename, "-c 1", "-r 16000", new_filename])
有关文档的更多信息 https://docs.python.org/3/library/subprocess.html
Note: Read the Security Considerations section before using
shell=True
.