yt-dlp下载前替换音频标题中|为-失效问题求助
问题:含'|'的歌曲标题无法替换后正确下载
标题包含'|'的歌曲无法提取Metadata,尝试将标题中的'|'替换为'-'后再下载,但运行代码后音频可正常下载,标题中的'|'却未被替换。
原代码如下:
import yt_dlp from mutagen.easyid3 import EasyID3 import os def download_and_tag_audio(): url = input("Enter audio url: ") genre = input("Genre of this music: ") directory = os.path.expanduser('~/Music/') ytdl_options = { 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '320', }], 'outtmpl': os.path.join(directory, '%(title)s.%(ext)s'), } ytdl = yt_dlp.YoutubeDL(ytdl_options) info = ytdl.extract_info(url, download=False) if info is None: print("Error 404!") else: # Replace '|' character in title info['title'] = info['title'].replace('|', '-') # Download audio ytdl.download(url) audio_file_path = ('/home/unish/Music/'+info['title']+'.mp3') metatag = EasyID3(audio_file_path) metatag['title'] = info['title'] metatag['artist'] = info['uploader'] metatag['genre'] = genre metatag.save() print("Download Completed.") download_and_tag_audio()
问题原因
- 修改
info['title']后,调用ytdl.download(url)时,yt-dlp会重新获取原始视频信息,而非使用你修改后的info对象,导致文件名仍用原始标题生成。 - 硬编码文件路径
/home/unish/Music/缺乏通用性,且若修改后的标题与实际生成的文件名不一致,会导致找不到文件无法写入Metadata。
修正后的代码
import yt_dlp from mutagen.easyid3 import EasyID3 import os def download_and_tag_audio(): url = input("Enter audio url: ") genre = input("Genre of this music: ") directory = os.path.expanduser('~/Music/') ytdl_options = { 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '320', }], 'outtmpl': os.path.join(directory, '%(title)s.%(ext)s'), } ytdl = yt_dlp.YoutubeDL(ytdl_options) info = ytdl.extract_info(url, download=False) if info is None: print("Error 404!") else: # 替换标题中的'|'为'-' info['title'] = info['title'].replace('|', '-') # 使用修改后的info对象下载,而非重新传url ytdl.process_info(info) # 从info中获取实际生成的文件路径,避免硬编码 audio_file_path = ytdl.prepare_filename(info).replace('.webm', '.mp3').replace('.m4a', '.mp3') metatag = EasyID3(audio_file_path) metatag['title'] = info['title'] metatag['artist'] = info['uploader'] metatag['genre'] = genre metatag.save() print("Download Completed.") download_and_tag_audio()
关键修改说明
- 用
ytdl.process_info(info)替代ytdl.download(url),直接使用修改后的info对象处理下载,确保文件名使用替换后的标题。 - 通过
ytdl.prepare_filename(info)获取实际生成的文件路径,再替换为mp3后缀(因为FFmpegExtractAudio会转换格式),避免硬编码路径导致的文件找不到问题。 - 移除了冗余的缩进,保持代码格式规范。
内容的提问来源于stack exchange,提问作者Unish Khadka
相关产品推荐
相关产品推荐

