Skip to content

Commit c3d3f0e

Browse files
committed
Allow the use of SoX if ffmpeg is not available
1 parent 794b2ff commit c3d3f0e

File tree

1 file changed

+39
-4
lines changed

1 file changed

+39
-4
lines changed

gentle/resample.py

Lines changed: 39 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import os
2+
import shutil
23
import subprocess
34
import tempfile
45

@@ -8,11 +9,9 @@
89
from .util.paths import get_binary
910

1011
FFMPEG = get_binary("ffmpeg")
12+
SOX = get_binary("sox")
1113

12-
def resample(infile, outfile, offset=None, duration=None):
13-
if not os.path.isfile(infile):
14-
raise IOError("Not a file: %s" % infile)
15-
14+
def resample_ffmpeg(infile, outfile, offset=None, duration=None):
1615
'''
1716
Use FFMPEG to convert a media file to a wav file sampled at 8K
1817
'''
@@ -38,6 +37,42 @@ def resample(infile, outfile, offset=None, duration=None):
3837
]
3938
return subprocess.call(cmd)
4039

40+
def resample_sox(infile, outfile, offset=None, duration=None):
41+
'''
42+
Use SoX to convert a media file to a wav file sampled at 8K
43+
'''
44+
if offset is None and duration is None:
45+
trim = []
46+
else:
47+
if offset is None:
48+
offset = 0
49+
trim = ['trim', str(offset)]
50+
if duration is not None:
51+
trim += [str(duration)]
52+
53+
cmd = [
54+
SOX,
55+
'--clobber',
56+
'-q',
57+
'-V1',
58+
infile,
59+
'-b', '16',
60+
'-c', '1',
61+
'-e', 'signed-integer',
62+
'-r', '8000',
63+
'-L',
64+
outfile
65+
] + trim
66+
return subprocess.call(cmd)
67+
68+
def resample(infile, outfile, offset=None, duration=None):
69+
if not os.path.isfile(infile):
70+
raise IOError("Not a file: %s" % infile)
71+
if shutil.which(FFMPEG):
72+
return resample_ffmpeg(infile, outfile, offset, duration)
73+
else:
74+
return resample_sox(infile, outfile, offset, duration)
75+
4176
@contextmanager
4277
def resampled(infile, offset=None, duration=None):
4378
with tempfile.NamedTemporaryFile(suffix='.wav') as fp:

0 commit comments

Comments
 (0)