-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScript.py
More file actions
803 lines (671 loc) · 34.6 KB
/
Copy pathScript.py
File metadata and controls
803 lines (671 loc) · 34.6 KB
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
import requests
import json
import time
import os
import re
import traceback
import sys
import urllib.parse
class MusicDownloader:
def __init__(self, base_url="http://localhost:5000"):
self.base_url = base_url
self.session = requests.Session()
# 音质选项映射
self.quality_options = {
"1": {"name": "standard", "desc": "标准音质", "format": "mp3"},
"2": {"name": "exhigh", "desc": "极高音质", "format": "mp3"},
"3": {"name": "lossless", "desc": "无损音质", "format": "flac"},
"4": {"name": "hires", "desc": "Hi-Res音质", "format": "flac"},
"5": {"name": "jyeffect", "desc": "高清环绕声", "format": "mp3"},
"6": {"name": "sky", "desc": "沉浸环绕声", "format": "mp3"},
"7": {"name": "jymaster", "desc": "超清母带", "format": "flac"}
}
def get_album_info(self, album_id):
"""获取专辑信息"""
url = f"{self.base_url}/Album"
params = {"id": album_id}
try:
print(f"正在请求专辑信息: {url}?id={album_id}")
response = self.session.get(url, params=params, timeout=30)
print(f"HTTP状态码: {response.status_code}")
response.raise_for_status()
data = response.json()
print(f"API响应状态: {data.get('status')}")
if data.get("status") == 200:
album_data = data["data"]["album"]
print(f"成功获取专辑: {album_data.get('name', '未知专辑')}")
print(f"专辑包含 {len(album_data.get('songs', []))} 首歌曲")
return album_data
else:
error_msg = data.get('data', {}).get('msg', '未知错误')
print(f"获取专辑信息失败: {error_msg}")
return None
except requests.exceptions.RequestException as e:
print(f"网络请求失败: {e}")
return None
except json.JSONDecodeError as e:
print(f"JSON解析失败: {e}")
print(f"响应内容: {response.text[:500]}...")
return None
except Exception as e:
print(f"获取专辑信息时发生未知错误: {e}")
traceback.print_exc()
return None
def get_playlist_info(self, playlist_id):
"""获取歌单信息"""
url = f"{self.base_url}/Playlist"
params = {"id": playlist_id}
try:
print(f"正在请求歌单信息: {url}?id={playlist_id}")
response = self.session.get(url, params=params, timeout=30)
print(f"HTTP状态码: {response.status_code}")
response.raise_for_status()
data = response.json()
print(f"API响应状态: {data.get('status')}")
if data.get("status") == 200:
playlist_data = data["data"]["playlist"]
print(f"成功获取歌单: {playlist_data.get('name', '未知歌单')}")
print(f"歌单包含 {len(playlist_data.get('tracks', []))} 首歌曲")
return playlist_data
else:
error_msg = data.get('data', {}).get('msg', '未知错误')
print(f"获取歌单信息失败: {error_msg}")
return None
except requests.exceptions.RequestException as e:
print(f"网络请求失败: {e}")
return None
except json.JSONDecodeError as e:
print(f"JSON解析失败: {e}")
print(f"响应内容: {response.text[:500]}...")
return None
except Exception as e:
print(f"获取歌单信息时发生未知错误: {e}")
traceback.print_exc()
return None
def get_downloads_folder(self):
"""获取用户下载文件夹路径"""
# 尝试获取用户主目录
if os.name == 'nt': # Windows
downloads_folder = os.path.join(os.path.expanduser('~'), 'Downloads')
else: # Linux/Mac
downloads_folder = os.path.join(os.path.expanduser('~'), 'Downloads')
# 如果下载文件夹不存在,使用当前工作目录
if not os.path.exists(downloads_folder):
downloads_folder = os.getcwd()
return downloads_folder
def create_safe_directory(self, base_path, folder_name):
"""安全地创建目录,处理权限问题"""
# 清理文件夹名称中的非法字符
safe_folder_name = re.sub(r'[<>:"/\\|?*]', '', folder_name)
full_path = os.path.join(base_path, safe_folder_name)
try:
os.makedirs(full_path, exist_ok=True)
print(f"成功创建目录: {full_path}")
return full_path
except PermissionError:
print(f"权限不足,无法在 {base_path} 创建目录")
# 尝试在当前工作目录创建
current_dir = os.getcwd()
fallback_path = os.path.join(current_dir, safe_folder_name)
try:
os.makedirs(fallback_path, exist_ok=True)
print(f"使用备用目录: {fallback_path}")
return fallback_path
except Exception as e:
print(f"创建备用目录也失败: {e}")
return None
except Exception as e:
print(f"创建目录失败: {e}")
return None
def get_file_extension(self, quality, content_type=""):
"""根据音质和内容类型确定文件扩展名"""
# 首先根据音质确定默认格式
quality_info = None
for q in self.quality_options.values():
if q["name"] == quality:
quality_info = q
break
default_ext = quality_info.get("format", "mp3") if quality_info else "mp3"
# 然后根据内容类型调整
content_type = content_type.lower()
if "flac" in content_type:
return "flac"
elif "mpeg" in content_type or "mp3" in content_type:
return "mp3"
elif "wav" in content_type:
return "wav"
elif "aac" in content_type or "m4a" in content_type:
return "m4a"
else:
return default_ext
def download_song(self, song_id, song_name, quality="lossless", save_dir="downloads"):
"""下载单首歌曲"""
url = f"{self.base_url}/download"
payload = {
"id": str(song_id),
"quality": quality
}
# 创建下载目录
try:
os.makedirs(save_dir, exist_ok=True)
except Exception as e:
print(f"创建目录失败: {e}")
# 尝试在用户下载文件夹中创建
downloads_folder = self.get_downloads_folder()
folder_name = os.path.basename(save_dir)
save_dir = self.create_safe_directory(downloads_folder, folder_name)
if not save_dir:
print("无法创建任何下载目录,下载终止")
return False
# 清理文件名中的非法字符
safe_name = re.sub(r'[<>:"/\\|?*]', '', song_name)
try:
print(f"正在下载歌曲: {song_name} (ID: {song_id}, 音质: {quality})")
response = self.session.post(url, json=payload, stream=True, timeout=60)
response.raise_for_status()
# 检查响应内容类型
content_type = response.headers.get('content-type', '').lower()
content_length = response.headers.get('content-length')
print(f"响应类型: {content_type}, 大小: {content_length} bytes")
# 尝试从响应头获取文件名
encoded_filename = response.headers.get('X-Download-Filename')
if encoded_filename:
filename = urllib.parse.unquote(encoded_filename)
print(f"使用服务器提供的文件名: {filename}")
else:
# 确定文件扩展名
file_ext = self.get_file_extension(quality, content_type)
filename = f"{safe_name}.{file_ext}"
filepath = os.path.join(save_dir, filename)
# 如果文件已存在,添加序号
counter = 1
original_filepath = filepath
while os.path.exists(filepath):
name, ext = os.path.splitext(original_filepath)
filepath = f"{name}_{counter}{ext}"
counter += 1
# 下载文件
file_size = 0
with open(filepath, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
file_size += len(chunk)
print(f"文件已保存: {filepath} ({file_size} bytes)")
# 检查服务器消息
download_message = response.headers.get('X-Download-Message')
if download_message:
print(f"服务器消息: {download_message}")
# 检查文件是否有效(至少有一定大小)
if file_size > 1024: # 假设大于1KB的文件是有效的
print(f"✓ 下载成功: {song_name}")
return True
else:
print(f"✗ 文件太小,可能下载失败: {song_name}")
# 删除无效文件
try:
os.remove(filepath)
except:
pass
return False
except requests.exceptions.RequestException as e:
print(f"✗ 下载失败: {song_name} - {e}")
return False
except Exception as e:
print(f"✗ 下载过程中出现错误: {song_name} - {e}")
traceback.print_exc()
return False
def extract_id(self, input_str, pattern):
"""从输入中提取ID"""
input_str = input_str.strip()
# 如果是纯数字,直接返回
if input_str.isdigit():
return input_str
# 尝试从URL中提取ID
if pattern in input_str:
match = re.search(f'{pattern}\\?id=(\\d+)', input_str)
if match:
return match.group(1)
# 其他格式的URL处理
if "http" in input_str:
# 尝试从各种URL格式中提取数字ID
matches = re.findall(r'/(\d+)(?:\?|$)', input_str)
if matches:
return matches[0]
return input_str
def extract_song_id(self, input_str):
"""从输入中提取歌曲ID"""
return self.extract_id(input_str, "song")
def batch_download_album(self, album_input, quality="lossless", save_dir=None, delay=1):
"""批量下载专辑中的所有歌曲"""
try:
# 提取专辑ID
album_id = self.extract_id(album_input, "album")
if not album_id:
print("无效的专辑ID或链接")
return
print(f"正在获取专辑信息: {album_id}")
album_info = self.get_album_info(album_id)
if not album_info:
print("无法获取专辑信息,请检查专辑ID是否正确")
return
# 设置保存目录
if save_dir is None:
# 使用专辑名称作为目录名,放在用户下载文件夹中
album_name = re.sub(r'[<>:"/\\|?*]', '', album_info.get("name", "未知专辑"))
downloads_folder = self.get_downloads_folder()
save_dir = self.create_safe_directory(downloads_folder, f"音乐下载/专辑/{album_name}")
if not save_dir:
print("无法创建下载目录,程序终止")
return
else:
# 用户指定了目录,尝试创建
try:
os.makedirs(save_dir, exist_ok=True)
except Exception as e:
print(f"创建指定目录失败: {e}")
# 使用备用目录
album_name = re.sub(r'[<>:"/\\|?*]', '', album_info.get("name", "未知专辑"))
downloads_folder = self.get_downloads_folder()
save_dir = self.create_safe_directory(downloads_folder, f"音乐下载/专辑/{album_name}")
if not save_dir:
print("无法创建任何下载目录,程序终止")
return
print(f"专辑: {album_info.get('name', '未知专辑')}")
print(f"艺术家: {album_info.get('artist', '未知艺术家')}")
print(f"歌曲数量: {len(album_info.get('songs', []))}")
print(f"音质: {quality}")
print(f"保存到: {save_dir}")
print("-" * 50)
# 检查歌曲列表是否存在
if 'songs' not in album_info or not album_info['songs']:
print("专辑中没有找到歌曲列表")
return
# 批量下载
success_count = 0
total_count = len(album_info["songs"])
for i, song in enumerate(album_info["songs"], 1):
try:
print(f"[{i}/{total_count}] 正在处理: {song.get('name', '未知歌曲')}")
# 检查歌曲数据是否完整
if 'id' not in song or 'name' not in song:
print(f"歌曲数据不完整,跳过: {song}")
continue
if self.download_song(song["id"], song["name"], quality, save_dir):
success_count += 1
# 添加延迟,避免请求过于频繁
if i < total_count and delay > 0:
print(f"等待 {delay} 秒...")
time.sleep(delay)
except Exception as e:
print(f"处理第 {i} 首歌曲时发生错误: {e}")
traceback.print_exc()
continue
print("-" * 50)
print(f"下载完成: {success_count}/{total_count} 首歌曲")
except Exception as e:
print(f"批量下载过程中发生严重错误: {e}")
traceback.print_exc()
input("按回车键继续...")
def batch_download_playlist(self, playlist_input, quality="lossless", save_dir=None, delay=1):
"""批量下载歌单中的所有歌曲"""
try:
# 提取歌单ID
playlist_id = self.extract_id(playlist_input, "playlist")
if not playlist_id:
print("无效的歌单ID或链接")
return
print(f"正在获取歌单信息: {playlist_id}")
playlist_info = self.get_playlist_info(playlist_id)
if not playlist_info:
print("无法获取歌单信息,请检查歌单ID是否正确")
return
# 设置保存目录
if save_dir is None:
# 使用歌单名称作为目录名,放在用户下载文件夹中
playlist_name = re.sub(r'[<>:"/\\|?*]', '', playlist_info.get("name", "未知歌单"))
downloads_folder = self.get_downloads_folder()
save_dir = self.create_safe_directory(downloads_folder, f"音乐下载/歌单/{playlist_name}")
if not save_dir:
print("无法创建下载目录,程序终止")
return
else:
# 用户指定了目录,尝试创建
try:
os.makedirs(save_dir, exist_ok=True)
except Exception as e:
print(f"创建指定目录失败: {e}")
# 使用备用目录
playlist_name = re.sub(r'[<>:"/\\|?*]', '', playlist_info.get("name", "未知歌单"))
downloads_folder = self.get_downloads_folder()
save_dir = self.create_safe_directory(downloads_folder, f"音乐下载/歌单/{playlist_name}")
if not save_dir:
print("无法创建任何下载目录,程序终止")
return
print(f"歌单: {playlist_info.get('name', '未知歌单')}")
print(f"创建者: {playlist_info.get('creator', '未知创建者')}")
print(f"歌曲数量: {len(playlist_info.get('tracks', []))}")
print(f"音质: {quality}")
print(f"保存到: {save_dir}")
print("-" * 50)
# 检查歌曲列表是否存在
if 'tracks' not in playlist_info or not playlist_info['tracks']:
print("歌单中没有找到歌曲列表")
return
# 批量下载
success_count = 0
total_count = len(playlist_info["tracks"])
for i, song in enumerate(playlist_info["tracks"], 1):
try:
print(f"[{i}/{total_count}] 正在处理: {song.get('name', '未知歌曲')}")
# 检查歌曲数据是否完整
if 'id' not in song or 'name' not in song:
print(f"歌曲数据不完整,跳过: {song}")
continue
if self.download_song(song["id"], song["name"], quality, save_dir):
success_count += 1
# 添加延迟,避免请求过于频繁
if i < total_count and delay > 0:
print(f"等待 {delay} 秒...")
time.sleep(delay)
except Exception as e:
print(f"处理第 {i} 首歌曲时发生错误: {e}")
traceback.print_exc()
continue
print("-" * 50)
print(f"下载完成: {success_count}/{total_count} 首歌曲")
except Exception as e:
print(f"批量下载过程中发生严重错误: {e}")
traceback.print_exc()
input("按回车键继续...")
def download_single_song(self, song_input, quality="lossless", save_dir=None):
"""下载单首歌曲"""
try:
# 提取歌曲ID
song_id = self.extract_song_id(song_input)
if not song_id:
print("无效的歌曲ID或链接")
return False
# 设置保存目录
if save_dir is None:
# 使用默认目录
downloads_folder = self.get_downloads_folder()
save_dir = self.create_safe_directory(downloads_folder, "音乐下载/单曲")
if not save_dir:
print("无法创建下载目录,程序终止")
return False
else:
# 用户指定了目录,尝试创建
try:
os.makedirs(save_dir, exist_ok=True)
except Exception as e:
print(f"创建指定目录失败: {e}")
# 使用备用目录
downloads_folder = self.get_downloads_folder()
save_dir = self.create_safe_directory(downloads_folder, "音乐下载/单曲")
if not save_dir:
print("无法创建任何下载目录,程序终止")
return False
print(f"正在下载单曲 (ID: {song_id})")
print(f"音质: {quality}")
print(f"保存到: {save_dir}")
print("-" * 50)
# 使用一个默认的歌曲名,实际文件名将从服务器响应头中获取
result = self.download_song(song_id, "单曲", quality, save_dir)
if result:
print("✓ 单曲下载完成!")
else:
print("✗ 单曲下载失败!")
return result
except Exception as e:
print(f"单曲下载过程中发生错误: {e}")
traceback.print_exc()
return False
def batch_download_from_txt(self, file_path, quality="lossless", save_dir=None, delay=1):
"""从TXT文件批量下载歌曲"""
try:
# 检查文件是否存在
if not os.path.exists(file_path):
print(f"文件不存在: {file_path}")
return False
# 读取TXT文件
with open(file_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
# 处理每一行,提取歌曲ID
song_ids = []
for line in lines:
line = line.strip()
if not line or line.startswith('#'): # 跳过空行和注释
continue
# 提取歌曲ID
song_id = self.extract_song_id(line)
if song_id and song_id.isdigit():
song_ids.append(song_id)
else:
print(f"跳过无效的歌曲ID: {line}")
if not song_ids:
print("TXT文件中没有找到有效的歌曲ID")
return False
# 设置保存目录
if save_dir is None:
# 使用默认目录
downloads_folder = self.get_downloads_folder()
# 使用文件名作为文件夹名
file_name = os.path.splitext(os.path.basename(file_path))[0]
save_dir = self.create_safe_directory(downloads_folder, f"音乐下载/TXT批量下载/{file_name}")
if not save_dir:
print("无法创建下载目录,程序终止")
return False
else:
# 用户指定了目录,尝试创建
try:
os.makedirs(save_dir, exist_ok=True)
except Exception as e:
print(f"创建指定目录失败: {e}")
# 使用备用目录
downloads_folder = self.get_downloads_folder()
file_name = os.path.splitext(os.path.basename(file_path))[0]
save_dir = self.create_safe_directory(downloads_folder, f"音乐下载/TXT批量下载/{file_name}")
if not save_dir:
print("无法创建任何下载目录,程序终止")
return False
print(f"从文件读取到 {len(song_ids)} 首歌曲")
print(f"音质: {quality}")
print(f"保存到: {save_dir}")
print("-" * 50)
# 批量下载
success_count = 0
total_count = len(song_ids)
for i, song_id in enumerate(song_ids, 1):
try:
print(f"[{i}/{total_count}] 正在处理歌曲ID: {song_id}")
# 使用歌曲ID作为临时名称,实际文件名将从服务器响应头中获取
if self.download_song(song_id, f"歌曲_{song_id}", quality, save_dir):
success_count += 1
# 添加延迟,避免请求过于频繁
if i < total_count and delay > 0:
print(f"等待 {delay} 秒...")
time.sleep(delay)
except Exception as e:
print(f"处理第 {i} 首歌曲时发生错误: {e}")
traceback.print_exc()
continue
print("-" * 50)
print(f"下载完成: {success_count}/{total_count} 首歌曲")
return success_count > 0
except Exception as e:
print(f"从TXT文件批量下载过程中发生错误: {e}")
traceback.print_exc()
return False
def main():
try:
downloader = MusicDownloader()
print("=== 音乐批量下载工具 ===")
print(f"默认下载位置: {downloader.get_downloads_folder()}/音乐下载/")
while True:
try:
print("\n请选择下载类型:")
print("1. 专辑下载")
print("2. 歌单下载")
print("3. 单曲下载")
print("4. 从TXT文件批量下载")
print("输入 'quit' 退出程序")
choice = input().strip()
if choice.lower() in ['quit', 'exit', 'q']:
break
if choice == "1":
print("\n请输入专辑ID或链接:")
input_id = input().strip()
if not input_id:
continue
print("请选择音质 (默认: lossless):")
for key, value in downloader.quality_options.items():
print(f"{key}. {value['name']} - {value['desc']}")
quality_choice = input().strip()
# 如果用户直接输入音质名称,使用它;否则从映射中获取
if quality_choice in downloader.quality_options:
quality = downloader.quality_options[quality_choice]["name"]
else:
# 检查是否是有效的音质名称
valid_qualities = [v["name"] for v in downloader.quality_options.values()]
if quality_choice in valid_qualities:
quality = quality_choice
else:
quality = "lossless" # 默认值
print(f"使用默认音质: {quality}")
print("请输入保存目录 (直接回车使用默认目录):")
save_dir = input().strip()
if not save_dir:
save_dir = None
print("请输入下载延迟秒数 (默认: 1秒):")
delay_input = input().strip()
try:
delay = float(delay_input) if delay_input else 1
except ValueError:
delay = 1
# 开始下载专辑
downloader.batch_download_album(
album_input=input_id,
quality=quality,
save_dir=save_dir,
delay=delay
)
elif choice == "2":
print("\n请输入歌单ID或链接:")
input_id = input().strip()
if not input_id:
continue
print("请选择音质 (默认: lossless):")
for key, value in downloader.quality_options.items():
print(f"{key}. {value['name']} - {value['desc']}")
quality_choice = input().strip()
# 如果用户直接输入音质名称,使用它;否则从映射中获取
if quality_choice in downloader.quality_options:
quality = downloader.quality_options[quality_choice]["name"]
else:
# 检查是否是有效的音质名称
valid_qualities = [v["name"] for v in downloader.quality_options.values()]
if quality_choice in valid_qualities:
quality = quality_choice
else:
quality = "lossless" # 默认值
print(f"使用默认音质: {quality}")
print("请输入保存目录 (直接回车使用默认目录):")
save_dir = input().strip()
if not save_dir:
save_dir = None
print("请输入下载延迟秒数 (默认: 1秒):")
delay_input = input().strip()
try:
delay = float(delay_input) if delay_input else 1
except ValueError:
delay = 1
# 开始下载歌单
downloader.batch_download_playlist(
playlist_input=input_id,
quality=quality,
save_dir=save_dir,
delay=delay
)
elif choice == "3":
print("\n请输入单曲ID或链接:")
input_id = input().strip()
if not input_id:
continue
print("请选择音质 (默认: lossless):")
for key, value in downloader.quality_options.items():
print(f"{key}. {value['name']} - {value['desc']}")
quality_choice = input().strip()
# 如果用户直接输入音质名称,使用它;否则从映射中获取
if quality_choice in downloader.quality_options:
quality = downloader.quality_options[quality_choice]["name"]
else:
# 检查是否是有效的音质名称
valid_qualities = [v["name"] for v in downloader.quality_options.values()]
if quality_choice in valid_qualities:
quality = quality_choice
else:
quality = "lossless" # 默认值
print(f"使用默认音质: {quality}")
print("请输入保存目录 (直接回车使用默认目录):")
save_dir = input().strip()
if not save_dir:
save_dir = None
# 开始下载单曲
downloader.download_single_song(
song_input=input_id,
quality=quality,
save_dir=save_dir
)
elif choice == "4":
print("\n请输入TXT文件路径:")
file_path = input().strip()
if not file_path:
continue
print("请选择音质 (默认: lossless):")
for key, value in downloader.quality_options.items():
print(f"{key}. {value['name']} - {value['desc']}")
quality_choice = input().strip()
# 如果用户直接输入音质名称,使用它;否则从映射中获取
if quality_choice in downloader.quality_options:
quality = downloader.quality_options[quality_choice]["name"]
else:
# 检查是否是有效的音质名称
valid_qualities = [v["name"] for v in downloader.quality_options.values()]
if quality_choice in valid_qualities:
quality = quality_choice
else:
quality = "lossless" # 默认值
print(f"使用默认音质: {quality}")
print("请输入保存目录 (直接回车使用默认目录):")
save_dir = input().strip()
if not save_dir:
save_dir = None
print("请输入下载延迟秒数 (默认: 1秒):")
delay_input = input().strip()
try:
delay = float(delay_input) if delay_input else 1
except ValueError:
delay = 1
# 开始从TXT文件批量下载
downloader.batch_download_from_txt(
file_path=file_path,
quality=quality,
save_dir=save_dir,
delay=delay
)
else:
print("无效选择,请重新输入")
except KeyboardInterrupt:
print("\n用户中断操作")
break
except Exception as e:
print(f"主循环发生错误: {e}")
traceback.print_exc()
continue
except Exception as e:
print(f"程序启动失败: {e}")
traceback.print_exc()
input("按回车键退出...")
if __name__ == "__main__":
main()