Python code to download and strip audio from youtube videos

This code helps in downloading youtube videos directly .The last part of the code helps in stripping the audio from the video . (I guess this is very helpful , as most of the times , you would just want to store the audio of your favorite song )

Very primitive code, which  I wrote recently  🙂

import urllib2
import re
import sys,os
video_data='%7C(.*?videoplayback.*?)%2C'
def download(url):
	headers={'User-Agent':None}
	req=urllib2.Request(url,None,headers)

	s=urllib2.urlopen(req).read()
	search=re.search(video_data,s)
	if search:
		flash_url=urllib2.unquote(search.group(1))
	req=urllib2.Request(flash_url,None,headers)
	file1=open('output','wb')
	req=urllib2.Request(flash_url,None,headers)
	s=urllib2.urlopen(req).read()
	file1.write(s)
	sys.stdout.flush()
	#this is to extract the audio from the video which was downloaded
	cmd='ffmpeg -i output -acodec libmp3lame -aq 4 audio.mp3'
	#need to download ffmpeg if the script doesnt work here
	os.system(cmd);
url=raw_input("Enter the youtube url\n")
download(url)

Further enhancing this code :
I would suggest instead of copying the entire content in the file at once, we can go about copying in blocks
and writing a progress bar and time to download.
Any more suggestions , please add it to the comments.

2 thoughts on “Python code to download and strip audio from youtube videos

  1. Thanks for the code. I ran it in the terminal and it worked without issue. I could see where a progress bar would be nice. stripping the audio with ffmpeg as a separate .mp3 file was a nice touch. Again, thanks.

Leave a comment