尝试使用 python 下载 YouTube 视频时出现错误

问题描述 投票:0回答:1

代码

我正在编写一个脚本,允许用户使用 yt-dlp 从 YouTube 手动选择和下载单独的视频和音频流。该脚本列出了可用的视频和音频格式,让用户选择所需的格式,然后使用 FFmpeg 合并它们。

完整代码如下:

import yt_dlp
import os
import subprocess

# Function to list and allow manual selection of video and audio formats
def download_and_merge_video_audio_with_selection(url, download_path):
    try:
        # Ensure the download path exists
        if not os.path.exists(download_path):
            os.makedirs(download_path)

        # Get available formats from yt-dlp
        ydl_opts = {'listformats': True}

        with yt_dlp.YoutubeDL(ydl_opts) as ydl:
            info_dict = ydl.extract_info(url, download=False)
            formats = info_dict.get('formats', [])

        # List available video formats (video only)
        print("\nAvailable video formats:")
        video_formats = [f for f in formats if f.get('vcodec') != 'none' and f.get('acodec') == 'none']
        for idx, f in enumerate(video_formats):
            resolution = f.get('height', 'unknown')
            filesize = f.get('filesize', 'unknown')
            print(f"{idx}: Format code: {f['format_id']}, Resolution: {resolution}p, Size: {filesize} bytes")

        # Let user select the desired video format
        video_idx = int(input("\nEnter the number corresponding to the video format you want to download: "))
        video_format_code = video_formats[video_idx]['format_id']

        # List available audio formats (audio only)
        print("\nAvailable audio formats:")
        audio_formats = [f for f in formats if f.get('acodec') != 'none' and f.get('vcodec') == 'none']
        for idx, f in enumerate(audio_formats):
            abr = f.get('abr', 'unknown')  # Audio bitrate
            filesize = f.get('filesize', 'unknown')
            print(f"{idx}: Format code: {f['format_id']}, Audio Bitrate: {abr} kbps, Size: {filesize} bytes")

        # Let user select the desired audio format
        audio_idx = int(input("\nEnter the number corresponding to the audio format you want to download: "))
        audio_format_code = audio_formats[audio_idx]['format_id']

        # Video download options (based on user choice)
        video_opts = {
            'format': video_format_code,  # Download user-selected video format
            'outtmpl': os.path.join(download_path, 'video.%(ext)s'),  # Save video as video.mp4
        }

        # Audio download options (based on user choice)
        audio_opts = {
            'format': audio_format_code,  # Download user-selected audio format
            'outtmpl': os.path.join(download_path, 'audio.%(ext)s'),  # Save audio as audio.m4a
        }

        # Download the selected video format
        print("\nDownloading selected video format...")
        with yt_dlp.YoutubeDL(video_opts) as ydl_video:
            ydl_video.download([url])

        # Download the selected audio format
        print("\nDownloading selected audio format...")
        with yt_dlp.YoutubeDL(audio_opts) as ydl_audio:
            ydl_audio.download([url])

        # Paths to the downloaded video and audio files
        video_file = os.path.join(download_path, 'video.webm')  # Assuming best video will be .mp4
        audio_file = os.path.join(download_path, 'audio.m4a')  # Assuming best audio will be .m4a
        output_file = os.path.join(download_path, 'final_output.mp4')  # Final merged file

        # FFmpeg command to merge audio and video
        ffmpeg_cmd = [
            'ffmpeg', '-i', video_file, '-i', audio_file, '-c', 'copy', output_file
        ]

        # Run FFmpeg to merge audio and video
        print("\nMerging video and audio...")
        subprocess.run(ffmpeg_cmd, check=True)

        print(f"\nDownload and merging complete! Output file: {output_file}")

    except Exception as e:
        print(f"An error occurred: {e}")

# Example usage
video_url = "https://www.youtube.com/watch?v=SOwk8FhfEZY"  # Replace with your desired video URL
download_path = 'C:/Users/vinod/Downloads/VideoDownload'  # Replace with your desired download path
download_and_merge_video_audio_with_selection(video_url, download_path)

说明:

该脚本首先列出给定 YouTube URL 中所有可用的视频格式(仅视频)和音频格式(仅音频)。

它允许用户手动选择他们喜欢的视频和音频格式。

下载选定的格式后,它使用 FFmpeg 将视频和音频流合并到单个文件中。

错误

在尝试运行上述代码时,我收到此错误:

Merging video and audio...
An error occurred: [WinError 2] The system cannot find the file specified

要求:

yt-dlp:

pip install yt-dlp

FFmpeg:确保您已安装 FFmpeg 并将其添加到系统的 PATH 中。

python python-3.x ffmpeg yt-dlp ffmpeg-python
1个回答
0
投票

该错误意味着您的系统找不到 FFmpeg。只需安装它并将其添加到系统的 PATH 即可。

© www.soinside.com 2019 - 2024. All rights reserved.