-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmake_lrc_music_m3u-Python2.py
260 lines (209 loc) · 7.36 KB
/
make_lrc_music_m3u-Python2.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# -*- encoding:utf-8 -*-
# 网易云音乐 lrc歌曲m3u生成器
# 版本: 4.2
import platform
import sys
reload(sys)
if platform.system() == u'Windows':
sys.setdefaultencoding('gbk')
else:
sys.setdefaultencoding('utf-8')
import codecs
import hashlib
import json
import os
import urllib
import urllib2
from sys import argv
if len(argv) < 2:
print "请传入歌单id"
sys.exit()
# 歌单id设置 设置为 argv[1] 将使用 " python make_lrc_music_m3u.py 歌单id " 这种方式传入
playlistId = argv[1]
# 播放列表存放位置
m3udir = u"./播放列表/"
# 相对于播放列表存放位置的 音乐存放位置
mp3dir_in_m3udir = u"../音乐/"
# 是否按m3u分类
if len(argv) > 2:
sortBym3u = True
else:
sortBym3u = False
# 是否下载歌词
downLrc = True
# 判断文件是否存在
def hasFile(fileName):
if fileName in listdir:
return True
else:
return False
# 半角转全角
def half2full(ustring):
rstring = ""
for uchar in ustring:
inside_code = ord(uchar)
if inside_code == 32:
inside_code = 12288
elif inside_code >= 32 and inside_code <= 126:
inside_code += 65248
rstring += unichr(inside_code)
return rstring
# 发送请求
def urlGetJsonLoad(url):
headers = {
'Accept':
'*/*',
'Accept-Language':
'zh-CN,zh;q=0.8,gl;q=0.6,zh-TW;q=0.4',
'Connection':
'keep-alive',
'Content-Type':
'application/x-www-form-urlencoded',
'Referer':
'http://music.163.com',
'Host':
'music.163.com',
'User-Agent':
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36'
}
req = urllib2.Request(url, headers=headers)
return json.load(urllib2.urlopen(req))
# 替换文件名不允许字符
def replaceName(name):
name = name.replace('?', half2full('?'))
name = name.replace('*', half2full('*'))
name = name.replace('/', half2full('/'))
name = name.replace('\\', half2full('\\'))
name = name.replace('<', half2full('<'))
name = name.replace('>', half2full('>'))
name = name.replace(':', half2full(':'))
name = name.replace('\"', half2full('\"'))
name = name.replace('|', half2full('|'))
name = name.replace('[', half2full('['))
name = name.replace(']', half2full(']'))
return name
# 获取歌词
def getLrc(tracksId):
url = 'http://music.163.com/api/song/lyric?lv=-1&tv=-1&id=' + tracksId
dataS = urlGetJsonLoad(url)
if dataS['code'] != 200:
ecode = bytes(dataS['code'])
print 'errorCode: ' + ecode
else:
if not dataS.has_key('lrc') or not dataS['lrc'].has_key('lyric') or dataS['lrc']['lyric'] == None:
return ''
if not dataS.has_key('tlyric') or not dataS['tlyric'].has_key('lyric') or dataS['tlyric']['lyric'] == None:
return dataS['lrc']['lyric']
# 按换行分割
lrcL = dataS['lrc']['lyric'].splitlines()
tlyricL = dataS['tlyric']['lyric'].splitlines()
tlyricD = {}
lrcStr = ''
# 分割翻译
for tlyric in tlyricL:
tl = tlyric.split(u']', 1)
# 防止有时间但翻译为空
if len(tl) > 1:
tlyricD[tl[0]] = tl[1]
# 合并歌词
for lrc in lrcL:
l = lrc.split(u']', 1)
if tlyricD.has_key(l[0]):
lrcStr += l[0] + u']' + l[1] + u'\t' + tlyricD[l[0]] + u'\n'
else:
lrcStr += lrc + u'\n'
return lrcStr
# 下载歌曲
def dowmMusic(tracksId, fileName):
url = 'http://music.163.com/song/media/outer/url?id=' + tracksId + '.mp3'
try:
print 'Download music: ' + fileName.replace(m3udir, '').replace(mp3dir, '')
except:
print 'Download music: '
try:
urllib.urlretrieve(url, fileName)
except:
print 'error'
# 写出文件
def writeToFile(name, text):
try:
print 'Write to file: ' + name.replace(m3udir, '').replace(mp3dir, '')
except:
print 'Write to file: '
try:
file = codecs.open(name, "w", "utf-8")
file.write(text)
file.close()
except:
print 'error'
# 生成播放列表
m3uText = "#EXTM3U"
def addPlaylist(mp3Title, mp3Name):
global m3uText
m3uText += u"\n#EXTINF:" + mp3Title + u"\n" + mp3dir.replace("/", "\\") + mp3Name
# 确保需要的文件夹
if not os.path.isdir(m3udir):
os.mkdir(m3udir)
if not os.path.isdir(m3udir + mp3dir_in_m3udir):
os.mkdir(m3udir + mp3dir_in_m3udir)
# 获取歌单
url = 'http://music.163.com/api/playlist/detail?id=' + playlistId
dataL = urlGetJsonLoad(url)
if dataL['code'] != 200:
ecode = bytes(dataL['code'])
print 'errorCode: ' + ecode
else:
m3uName = replaceName(dataL['result']['name'])
allNum = len(dataL['result']['tracks'])
nowNum = 0
# 如按歌单分文件夹,不存在文件夹就创建
if sortBym3u:
mp3dir = mp3dir_in_m3udir + m3uName + u"/"
if not os.path.isdir(m3udir + mp3dir):
os.mkdir(m3udir + mp3dir)
else:
mp3dir = mp3dir_in_m3udir
# 查找所有文件
listdir = os.listdir(m3udir + mp3dir)
# 循环歌单
for tracks in dataL['result']['tracks']:
nowNum += 1
print bytes(nowNum) + '/ ' + bytes(allNum)
fileName = ''
fileNameAndroid = ''
# 循环歌手
i = len(tracks['artists']) - 1
for artist in tracks['artists']:
if i > 0:
fileName += artist['name'] + u","
fileNameAndroid += artist['name'] + u" "
i -= 1
else:
fileName += artist['name']
fileNameAndroid += artist['name']
fileName += u" - " + tracks['name']
fileName = replaceName(fileName)
tid = bytes(tracks['id'])
# 存在歌曲文件跳过
if not hasFile(fileName + u".mp3"):
# 如果是按照空格分隔歌手,例如Android端
fileNameAndroid += u" - " + tracks['name'].strip()
fileNameAndroid = replaceName(fileNameAndroid.replace('/',' ').replace('*',' ').replace('+', half2full('+')).replace('\"',u'”'))
if fileNameAndroid != fileName and hasFile(fileNameAndroid):
try:
print 'Rename file: ' + fileNameAndroid + u".mp3"
except:
print 'Rename file: '
os.rename(m3udir + mp3dir + fileNameAndroid + u".mp3", m3udir + mp3dir + fileName + u".mp3")
else:
dowmMusic(tid, m3udir + mp3dir + fileName + u".mp3")
# 如果需要下载歌词,不存在歌词就下载
if downLrc:
if not hasFile(fileName + u".lrc"):
lrcS = getLrc(tid)
if len(lrcS) > 0:
writeToFile(m3udir + mp3dir + fileName + u".lrc", lrcS)
# 添加到播放列表
addPlaylist(tracks['name'], fileName + u".mp3")
# 写播放列表文件
writeToFile(m3udir + m3uName + u".m3u", m3uText)