Python开发的YouTube视频下载APP无声音问题求助
YouTube视频下载APP无声音问题解决
我用Python开发了一款YouTube视频下载APP,基于customtkinter和tkinter库实现,但下载后的视频没有声音。APP及已下载视频截图如下:
下载功能代码
def download_video(): url = entry_url.get() resolution = resolution_var.get() try: yt = YouTube(url) stream = yt.streams.filter(res=resolution).first() # Download the video into a specific directory os.path.join("downloads", f"{yt.title}.mp4") stream.download(output_path="downloads") except: print("")
分辨率选择框代码
# Create a resolution combo box resolutions = ["1080", "720p", "360p", "240p"] resolution_var = ctk.StringVar() resolution_combobox = ttk.Combobox(content_frame, values=resolutions, textvariable=resolution_var) resolution_combobox.pack(pady=(10, 5)) resolution_combobox.set("1080p")
问题原因分析
- 分辨率格式不统一:下拉选项里存在
"1080"(不带p)和"1080p"(带p)两种格式,导致筛选视频流时匹配错误,大概率拿到仅含画面的纯视频流。 - 未筛选含音频的流:YouTube高分辨率视频通常将画面和音频拆分为独立流,直接用
filter(res=resolution).first()选中的几乎都是无音频的纯视频流。
修复方案
1. 统一分辨率选项格式
先修正下拉框的选项格式,避免匹配偏差:
resolutions = ["1080p", "720p", "360p", "240p"]
2. 选择音视频合并流(最高支持720p)
如果不需要1080p以上分辨率,直接筛选progressive=True的流,这类流是音视频预合并的,下载后可直接播放:
def download_video(): url = entry_url.get() resolution = resolution_var.get() try: yt = YouTube(url) # 筛选对应分辨率的音视频合并流 stream = yt.streams.filter(res=resolution, progressive=True).first() # 无对应分辨率时,自动选最高清的合并流 if not stream: stream = yt.streams.filter(progressive=True).order_by('resolution').desc().first() stream.download(output_path="downloads") except Exception as e: print(f"下载出错:{str(e)}")
3. 下载高分辨率视频+音频并合并(支持1080p及以上)
如果需要1080p及更高分辨率,需分别下载视频流和音频流,再用FFmpeg合并:
- 先安装依赖库:
pip install ffmpeg-python
- 修改下载函数:
import os import ffmpeg def download_video(): url = entry_url.get() resolution = resolution_var.get() try: yt = YouTube(url) # 获取对应分辨率的纯视频流 video_stream = yt.streams.filter(res=resolution, only_video=True).first() # 获取最高质量的音频流 audio_stream = yt.streams.filter(only_audio=True).order_by('abr').desc().first() # 无对应分辨率视频流时,选最高清的 if not video_stream: video_stream = yt.streams.filter(only_video=True).order_by('resolution').desc().first() # 下载临时文件 temp_video = video_stream.download(output_path="downloads", filename="temp_video.mp4") temp_audio = audio_stream.download(output_path="downloads", filename="temp_audio.mp4") # 合并音视频(直接复制编码,不重新压缩) output_file = os.path.join("downloads", f"{yt.title}.mp4") ffmpeg.input(temp_video).input(temp_audio).output(output_file, vcodec='copy', acodec='copy').run() # 删除临时文件 os.remove(temp_video) os.remove(temp_audio) except Exception as e: print(f"下载出错:{str(e)}")
内容的提问来源于stack exchange,提问作者Mohamed Farag
相关产品推荐
相关产品推荐

