Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import tempfile
- import subprocess
- from twisted.internet import defer
- from twisted.internet.utils import getProcessOutputAndValue
- class AudioConversionError(Exception): pass
- def _is_exe(fname):
- return os.path.isfile(fname) and os.access(fname, os.X_OK)
- def _which(exename):
- for path in os.environ['PATH'].split(os.pathsep):
- fname = os.path.join(path, exename)
- if _is_exe(fname):
- return fname
- return None
- def _ffmpeg_or_avconv():
- return _which('ffmpeg') or _which('avconv') or None
- def _convert_audio(data, ffmpeg_args):
- fd, tmpname = tempfile.mkstemp()
- os.close(fd)
- try:
- exe = _ffmpeg_or_avconv()
- if exe is None:
- raise AudioConversionError('No ffmpeg of avconv installed')
- args = [exe, '-i', 'pipe:0', '-y' ]
- args.extend(ffmpeg_args)
- args.append(tmpname)
- ffmpeg = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
- ffmpeg.communicate(data)
- if ffmpeg.returncode != 0:
- raise AudioConversionError()
- with open(tmpname, 'rb') as f:
- return f.read()
- finally:
- os.unlink(tmpname)
- @defer.inlineCallbacks
- def _convert_audio_async(data, ffmpeg_args):
- fd, tmpinput = tempfile.mkstemp()
- os.close(fd)
- fd, tmpoutput = tempfile.mkstemp()
- os.close(fd)
- try:
- exe = _ffmpeg_or_avconv()
- if exe is None:
- raise AudioConversionError('No ffmpeg or avconv installed')
- with open(tmpinput, 'wb') as f:
- f.write(data)
- args = ['-i', tmpinput, '-y'] + ffmpeg_args + [tmpoutput]
- out, err, code = yield getProcessOutputAndValue(exe, args)
- if code != 0:
- raise AudioConversionError(err)
- with open(tmpoutput, 'rb') as f:
- return f.read()
- finally:
- os.unlink(tmpinput)
- os.unlink(tmpoutput)
- # ADPCM WAV 1ch s16
- _adpcm_args = [
- '-f', 'wav',
- '-acodec', 'adpcm_ima_wav',
- '-ac', '1',
- '-ar', '16000',
- ]
- _mp3_args = [
- '-f', 'mp3',
- '-b', '160k',
- '-id3v2_version', '0',
- ]
- def convert_to_adpcm(data):
- """ Takes arbitrary audio data and converts it to """
- return _convert_audio(data, _adpcm_args)
- def convert_to_mp3(data):
- return _convert_audio(data, _mp3_args)
- def convert_to_adpcm_async(data):
- return _convert_audio_async(data, _adpcm_args)
- def convert_to_mp3_async(data):
- return _convert_audio_async(data, _mp3_args)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement