-
Notifications
You must be signed in to change notification settings - Fork 0
/
music.py
90 lines (71 loc) · 2.67 KB
/
music.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# import all the library used
import re, urllib, os, sys
import lxml
from lxml import etree
import threading
from multiprocessing import Process
# determine python version
version = sys.version_info[0]
# set user_input and import modules for correct version of python
if version == 2: # python 2.x
user_input = raw_input
import urllib2
urlopen = urllib2.urlopen # open a url
encode = urllib.urlencode # encode a search line
retrieve = urllib.urlretrieve # retrieve url info
cleanup = urllib.urlcleanup() # cleanup url cache
else: # python 3.x
user_input = input
import urllib.request
import urllib.parse
urlopen = urllib.request.urlopen
encode = urllib.parse.urlencode
retrieve = urllib.request.urlretrieve
cleanup = urllib.request.urlcleanup()
# function to retrieve video title from provided link
def video_title(url):
try:
webpage = urlopen(url).read()
title = str(webpage).split('<title>')[1].split('</title>')[0]
except:
title = 'Youtube Song'
return title
# download directly with a song name or link
def single_download(string):
song = " ".join(string)
if "youtube.com/" not in song:
# try to get the search result and exit upon error
try:
query_string = encode({"search_query" : song})
html_content = urlopen("http://www.youtube.com/results?" + query_string)
if version == 3: # if using python 3.x
search_results = re.findall(r'href=\"\/watch\?v=(.{11})', html_content.read().decode())
else: # if using python 2.x
search_results = re.findall(r'href=\"\/watch\?v=(.{11})', html_content.read())
except:
print('Network Error')
return None
# make command that will be later executed and rename file to hello.mp3
command = 'youtube-dl --embed-thumbnail --no-warnings --extract-audio --audio-format mp3 -o "hello.%(ext)s" ' + search_results[0]
try: # Try downloading song
print('Retrieving %s' % song)
os.system(command)
print("\n\n")
link = "http://www.youtube.com/watch?v="+str(search_results[0])
song_title=video_title(link)
print(link)
#print(song_title)
music=os.system('mpg321 hello.mp3 -quiet')
print(music)
os.remove("hello.mp3")
except:
print('Error downloading %s' % song)
return "Song stops :("
# main guts of the program
class Music(object):
def main(string):
t1=os.fork();
if t1==0:
single_download(string);
else:
return "Hope you will be enjoying after a while"