我正在使用 youtube-dl 和 Python 下载 mp4 视频(包含声音/音频);我得到了 mp4 视频,但是,我无法设置正确的 ydl 选项来获取有声视频。
我的目标是下载 mp4 格式(质量为 240p 或 360p)的有声视频。
以下是我尝试过的不同 ydl 选项 - 所有这些组合都可以获得视频,但是没有声音:
ydl_opts = {'format': 'bestvideo[height<=480]+bestaudio[ext=mp4]/best'}
ydl_opts = {'format': 'bestvideo[height<=480]/best'}
ydl_opts = {'format': 'bestvideo[ext=mp4]+bestaudio[ext=mp4]/mp4+best[height<=480]'}
我尝试过:
是否有任何更容易遵循的文档来设置 ydl 选项以实现上述目标?
这是我的完整代码:
# Library import:
from yt_dlp import YoutubeDL
# Variables:
amount = 8 # Quantity of videos per page - next, research how to make search pagination.
urlFound = "" # Testing - this is the url of the video to download.
valid_formats = ["133", "134"] # Acceptable formats: 240p or 360p.
# ydl options.
# Sources:
# https://stackoverflow.com/q/60489888/12511801
# https://stackoverflow.com/a/49222737/12511801
#ydl_opts = {'format': 'bestvideo[height<=480]+bestaudio[ext=mp4]/best'}
#ydl_opts = {'format': 'bestvideo[height<=480]/best'}
ydl_opts = {'format': 'bestvideo[ext=mp4]+bestaudio[ext=mp4]/mp4+best[height<=480]'}
# Input the search term:
searchTerm = input("Please enter the search term: ")
# Validate input -> field cannot be empty:
while (len(searchTerm.strip()) == 0):
searchTerm = input("Field cannot be empty - please enter the search term: ")
# Use ydl for search videos:
with YoutubeDL(ydl_opts) as ydl:
try:
info = ydl.extract_info(f"ytsearch{amount}:{searchTerm}", download=False, ie_key="YoutubeSearch")
if (len(info["entries"]) == 0):
print("No results for (" + searchTerm + ")")
else:
print("Checking " + str(len(info["entries"])) + " results: ")
# Loop the results and verify if a valid video is found:
for indx, videoResult in enumerate(info["entries"]):
# Loop for valid format(s) available:
for frm_in_video in videoResult["formats"]:
if (str(frm_in_video['format_id']) in valid_formats):
urlFound = frm_in_video['url']
break # Video found.
# Verify if the video was found:
if (len(urlFound.strip()) == 0):
print("No valid video found - use next page and see more results")
else:
print("This is the valid video: " + urlFound)
except Exception as ex:
print("Error at searching videos. See details bellow")
print(str(ex))
经过更多测试,我将 ydl 选项保留如下:
ydl_opts = {'format': 'bestvideo[ext=mp4]+bestaudio[ext=mp4]/mp4+best[height<=480]'}
然后,我进一步修改了源代码,以便在视频找到的单独变量中设置。
# Variable that will store the video found. It will be a <dict> type value.
videoFound = None
接下来,(一旦检测到所需的视频),我设置在上一行中创建的
videoFound
的值:
# Loop the results and verify if a valid video is found:
for indx, videoResult in enumerate(info["entries"]):
# Loop for valid format(s) available:
for frm_in_video in videoResult["formats"]:
if (str(frm_in_video['format_id']) in valid_formats):
# Video found.
videoFound = videoResult
break # No need for keep looking further.
最后,当我验证是否找到任何视频时,我读取了
videoFound
变量=这是一个字典。
# Verify if the video was found:
if (len(urlFound.strip()) == 0):
print("No valid video found - use next page")
else:
try:
if (videoFound is not None):
print("Title: " + videoFound['title'])
# This is the video - for some reason,
# while using (bestaudio[ext=m4a]) - as suggested in the comment -
# Link: https://stackoverflow.com/questions/70744328/how-to-specify-ydl-options-for-download-video-with-audio?noredirect=1#comment125064688_70744328
# the returned URL is a "dash" video, but, with no sound, so,
# I rather get the values from the "videoFound" variable:
try:
print("URL: " + videoFound['url'])
except Exception as ex:
print("This is the valid video: " + urlFound)
print("Webpage URL: " + videoFound['webpage_url'])
print("Video ID: " + videoFound['id'])
print("Duration: " + videoFound['duration_string'])
print("Published at: " + videoFound['upload_date'])
print("View count: " + str(videoFound['view_count']))
print("Uploader: " + videoFound['uploader'])
print("Channel ID: " + videoFound['channel_id'])
print("Channel URL: " + videoFound['channel_url'])
print("Resolution: " + videoFound['resolution'])
else:
# Optional - show the url get in the "urlFound" variable:
print("This is the valid video: " + urlFound)
except Exception as ex:
print("Error at getting information from video found:")
print(str(ex))
使用格式: ydl_opts = {'格式': '最佳视频+最佳音频/最佳'} 您需要从 _https://ffmpeg.org/ 下载适合您操作系统的 ffmpeg,解压 bin 文件夹并将 exe 文件复制到您的项目文件夹。无需在 python 中安装 ffmpeg 库。