Skip to content

Instantly share code, notes, and snippets.

@ritiek
Last active April 9, 2024 19:06
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ritiek/c98452d8dcf062a63a70fe4631099419 to your computer and use it in GitHub Desktop.
Save ritiek/c98452d8dcf062a63a70fe4631099419 to your computer and use it in GitHub Desktop.
Using FFmpeg to read input via stdin in Python
# pip install pytube3
import pytube
import urllib.request
import subprocess
content = pytube.YouTube("https://www.youtube.com/watch?v=YQHsXMglC9A")
streams = content.streams.filter(only_audio=True).order_by("abr").desc()
response = urllib.request.urlopen(streams[0].url)
def download_and_convert_sequentially():
with open("input.opus", "wb") as fout:
fout.write(response.read())
command = ("ffmpeg", "-y", "-i", "input.opus", "output.wav")
process = subprocess.Popen(command)
process.wait()
def download_and_convert_parallely():
command = ("ffmpeg", "-y", "-i", "-", "output.wav")
process = subprocess.Popen(command, stdin=subprocess.PIPE)
while True:
chunk = response.read(16 * 1024)
if not chunk:
break
process.stdin.write(chunk)
process.stdin.close()
process.wait()
# download_and_convert_sequentially()
download_and_convert_parallely()
@dagrooms52
Copy link

I've been looking for download_and_convert_parallely() all day, thank you!
I was originally using the ffmpeg-python library's run_async() function, trying to do a similar process.stdin.write(chunk) but the pipe closed after the first call to stdin.write, I think their implementation is specific to "pipe:" input.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment