如何为下载带音频的视频指定 ydl 选项?

How to specify ydl options for download video with audio?

我正在使用 youtube-dl 和 Python 下载 mp4 视频(包含 sound/audio);我得到了 mp4 视频,但是,我无法设置正确的 ydl 选项来获得有声视频。

My goal is to download a video in mp4 format (with quality 240p or 360p) with sound.

以下是我尝试过的不同 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: 
# 
# 
#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: 
      # 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))