I currently have a function that runs ffmpeg enconder on a flv stream from youtube.
def console(cmd, add_newlines=False):
p = Popen(cmd, shell=True, stdout=PIPE)
while True:
data = p.stdout.readline()
if add_newlines:
data += str('\n')
yield data
p.poll()
if isinstance(p.returncode, int):
if p.returncode > 0:
# return code was non zero, an error?
print 'error:', p.returncode
break
This works fine when I run the ffmpeg command and have it output to a file. The file is playable.
mp3 = console('ffmpeg -i "%s" -acodec libmp3lame -ar 44100 -f mp3 test.mp3' % video_url, add_newlines=True)
But when I have ffmpeg output to stdout via - instead of test.mp3, and stream that response. The file streams fine, is the correct size. But does not play correctly. Sounds chopy, and when I check the properties of the file it doesn't show the data of it as it does with test.mp3
@app.route('/test.mp3')
def generate_large_mp3(path):
mp3 = console('ffmpeg -i "%s" -acodec libmp3lame -ar 44100 -f mp3 -' % video_url, add_newlines=True)
return Response(stream_with_context(mp3), mimetype="audio/mpeg3",
headers={"Content-Disposition":
"attachment;filename=test.mp3"})
Is there something I am missing?
consolefunction? Is it from a third-party library?subprocessfrom python to run ffmpeg to do the conversion..readline()returns a string with the newline already (unless the last line doesn't end with a newline). (2)str('\n')is pointless:'\n'by itself is alreadystrobject; unless there isfrom __future__ import unicode_literalson Python 2. (3) Don't call.poll()in a loop: here's a correct way to read text lines from a subprocessadd_newlines=Trueshould corrupt your binary mp3 data unless mp3 allows to double all'\n'in the stream.