11import os
2+ import shutil
23import subprocess
34import tempfile
45
89from .util .paths import get_binary
910
1011FFMPEG = 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
4277def resampled (infile , offset = None , duration = None ):
4378 with tempfile .NamedTemporaryFile (suffix = '.wav' ) as fp :
0 commit comments