Microsoft MVP성태의 닷넷 이야기
닷넷: 2367. C# - Youtube 동영상 다운로드 (YoutubeExplode 패키지) [링크 복사], [링크+제목 복사],
조회: 137
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일

C# - Youtube 동영상 다운로드 (YoutubeExplode 패키지)

사실 예전에도 한 번 소개해 드렸는데,

YoutubeExplode
; https://www.sysnet.pe.kr/2/0/13637#youtube_explode

github/YoutubeExplode
; https://github.com/Tyrrrz/YoutubeExplode

nuget/YoutubeExplode
; https://www.nuget.org/packages/YoutubeExplode

근래 들어 Youtube 측의 정책에 변화가 있어 사용법이 쉽지 않아졌습니다. (그러니까, 이 문제는 비단 YoutubeExplode 패키지뿐만 아니라 다른 라이브러리들도 모두 동일한 현상을 겪게 됩니다.)

Unable to download video (403 Forbidden) #853
; https://github.com/Tyrrrz/YoutubeExplode/issues/853

위의 이슈를 정리해 보면, Youtube 측에서 Rate Limit(요청 제한)을 적용했기 때문에 요청이 차단되는 현상이 발생한다는 건데요, 실제로 아래의 코드로만 테스트를 해도,

YoutubeClient youtube = new YoutubeClient();
var streamManifest = await youtube.Videos.Streams.GetManifestAsync(url);

어떤 경우에는 정상적으로 동작하지만, 어떤 경우에는 아래와 같은 오류가 발생합니다.

System.Net.Http.HttpRequestException: Response status code does not indicate success: 403 (Forbidden).
   at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
   at YoutubeExplode.Videos.Streams.StreamClient.TryGetContentLengthAsync(IStreamData streamData, String url, CancellationToken cancellationToken) in /_/YoutubeExplode/Videos/Streams/StreamClient.cs:line 82
   at YoutubeExplode.Videos.Streams.StreamClient.GetStreamInfosAsync(IEnumerable`1 streamDatas, CancellationToken cancellationToken)+MoveNext() in /_/YoutubeExplode/Videos/Streams/StreamClient.cs:line 115
   at YoutubeExplode.Videos.Streams.StreamClient.GetStreamInfosAsync(IEnumerable`1 streamDatas, CancellationToken cancellationToken)+System.Threading.Tasks.Sources.IValueTaskSource<System.Boolean>.GetResult()
   at YoutubeExplode.Utils.Extensions.AsyncCollectionExtensions.ToListAsync[T](IAsyncEnumerable`1 source) in /_/YoutubeExplode/Utils/Extensions/AsyncCollectionExtensions.cs:line 49
   at YoutubeExplode.Utils.Extensions.AsyncCollectionExtensions.ToListAsync[T](IAsyncEnumerable`1 source) in /_/YoutubeExplode/Utils/Extensions/AsyncCollectionExtensions.cs:line 49
   at YoutubeExplode.Videos.Streams.StreamClient.GetStreamInfosAsync(VideoId videoId, PlayerResponse playerResponse, CancellationToken cancellationToken) in /_/YoutubeExplode/Videos/Streams/StreamClient.cs:line 230
   at YoutubeExplode.Videos.Streams.StreamClient.GetStreamInfosAsync(VideoId videoId, CancellationToken cancellationToken) in /_/YoutubeExplode/Videos/Streams/StreamClient.cs:line 275
   at YoutubeExplode.Videos.Streams.StreamClient.GetManifestAsync(VideoId videoId, CancellationToken cancellationToken) in /_/YoutubeExplode/Videos/Streams/StreamClient.cs:line 307
   at ConsoleApp1.Program.GetLink(String url)

이로 인해, 연속적인 요청에 대해 정상 동작한다는 보장이 없으므로 귀찮아도 재시도를 수행하도록 코드를 작성해야 합니다.

YoutubeClient youtube = new YoutubeClient();
StreamManifest streamManifest = await GetStreamManifest(youtube, url);

private static async Task<StreamManifest> GetStreamManifest(YoutubeClient youtube, string url)
{
    while (true)
    {
        try
        {
            return await youtube.Videos.Streams.GetManifestAsync(url);
        }
        catch (Exception)
        {
        }
        await Task.Delay(5000);
    }
}




이 외에도 정책 변경이 하나 더 있다면, Audio + Video가 합쳐진 스트림이 더 이상 제공되지 않는다는 점입니다.

var muxedStreams = streamManifest.GetMuxedStreams(); // 결과가 없음

즉, 각각 다운로드를 해야 하는데, 어쩌면 그것 역시 Rate Limit 정책이 걸려 있을지 모르니 재시도를 고려해야 할 것 같습니다. 그래서... 결국 이런 식으로 코드가 나와야 합니다.

using YoutubeExplode;
using YoutubeExplode.Videos;
using YoutubeExplode.Videos.Streams;

namespace ConsoleApp1;

// Install-Package YoutubeExplode
internal class Program
{
    static async Task Main(string[] args)
    {
        YoutubeClient youtube = new YoutubeClient();
        string url = "https://youtu.be/90HFIm2Reqk";
        string title = await GetVideoTitle(youtube, url);
        StreamManifest streamManifest = await GetStreamManifest(youtube, url);
        string videoFile = await DownloadVideo(youtube, streamManifest, title, url);
        string audioFile = await DownloadAudio(youtube, streamManifest, title, url);
    }

    private static async Task<StreamManifest> GetStreamManifest(YoutubeClient youtube, string url)
    {
        StreamManifest? streamManifest = null;
        Console.WriteLine("Fetching stream manifest...");

        while (true)
        {
            try
            {
                streamManifest = await youtube.Videos.Streams.GetManifestAsync(url);
                break;
            }
            catch (Exception)
            {
                Console.Write($".");
            }
            await Task.Delay(5000);
        }

        Console.WriteLine();
        return streamManifest;
    }

    static async Task<string> GetVideoTitle(YoutubeClient youtube, string url)
    {
        Video? video = null;
        Console.WriteLine("Fetching video info...");
        while (true)
        {
            try
            {
                video = await youtube.Videos.GetAsync(url);
                break;
            }
            catch (Exception)
            {
                Console.Write($".");
            }
            await Task.Delay(5000);
        }

        if (video == null)
        {
            return "";
        }

        string title = video.Title;
        foreach (char c in Path.GetInvalidFileNameChars())
        {
            title = title.Replace(c, '_');
        }

        return title;
    }

    static async Task<string> DownloadVideo(YoutubeClient youtube, StreamManifest streamManifest, string title, string url)
    {
        var videoStreams = streamManifest.GetVideoStreams();
        IVideoStreamInfo? candidate = null;
        IVideoStreamInfo? mp4stream = null;

        foreach (var streamInfo in videoStreams)
        {
            VideoOnlyStreamInfo? vosi = streamInfo as VideoOnlyStreamInfo;
            if (vosi == null)
            {
                continue;
            }

            candidate = streamInfo;
            if (streamInfo.Container == Container.Mp4 && streamInfo.VideoResolution.Width == 1920)
            {
                mp4stream = streamInfo;
                break;
            }
        }

        if (mp4stream == null)
        {
            if (candidate == null)
            {
                return string.Empty;
            }

            mp4stream = candidate;
        }

        Console.WriteLine($"{mp4stream}: Downloading Video...");
        string fileName = $"{title}.{mp4stream.Container}";
        while (true)
        {
            try
            {
                await youtube.Videos.Streams.DownloadAsync(mp4stream, fileName);
                break;
            }
            catch (Exception)
            {
                Console.Write($".");
            }

            await Task.Delay(5000);
        }

        return fileName;
    }


    private static async Task<string> DownloadAudio(YoutubeClient youtube, StreamManifest streamManifest, string title, string url)
    {
        var audioStreams = streamManifest.GetAudioOnlyStreams();
        IAudioStreamInfo? candidate = null;
        IAudioStreamInfo? mp3stream = null;

        foreach (var streamInfo in audioStreams)
        {
            AudioOnlyStreamInfo? aosi = streamInfo as AudioOnlyStreamInfo;
            if (aosi == null)
            {
                continue;
            }
            
            candidate = streamInfo;

            if (streamInfo.Container == Container.Mp3 && streamInfo.Bitrate.KiloBitsPerSecond >= 128)
            {
                mp3stream = streamInfo;
                break;
            }
        }

        if (mp3stream == null)
        {
            if (candidate == null)
            {
                return string.Empty;
            }
            mp3stream = candidate;
        }

        Console.WriteLine($"{mp3stream}: Downloading Audio...");
        string fileName = $"{title}.{mp3stream.Container}";

        while (true)
        {
            try
            {
                await youtube.Videos.Streams.DownloadAsync(mp3stream, fileName);
                break;
            }
            catch (Exception)
            {
                Console.Write($".");
            }

            await Task.Delay(5000);
        }

        return fileName;
    }
}

이렇게 하면... 뭐 그런대로 잘 동작합니다. ^^ 단지, 좀 멋있게 하고 싶다면 Polly 등을 이용해 재시도를 구현해도 좋을 것입니다. ^^




마지막으로, Audio와 Video를 따로 받았으니 이제 합쳐야 할 텐데요, 이 부분은 지난 글에서 설명한 FFMpegCore 패키지를 이용해 간단하게 해결할 수 있습니다.

// Install-Package FFmpegCore
using FFMpegCore;

FFMpeg.ReplaceAudio(videoFile, audioFile, $"{title}-final.mp4");

(첨부 파일은 이 글의 예제 코드를 포함합니다.)





[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 10/6/2025]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13797정성태11/1/202411229C/C++: 185. C++ - 문자열의 대소문자를 변환하는 transform + std::tolower/toupper 방식의 문제점파일 다운로드1
13796정성태10/31/20249998C/C++: 184. C++ - ICU dll을 이용하는 예제 코드 (Windows)파일 다운로드1
13795정성태10/31/20249302Windows: 268. Windows - 리눅스 환경처럼 공백으로 끝나는 프롬프트 만들기
13794정성태10/30/20249795닷넷: 2307. C# - 윈도우에서 한글(및 유니코드)을 포함한 콘솔 프로그램을 컴파일 및 실행하는 방법
13793정성태10/28/20249591C/C++: 183. C++ - 윈도우에서 한글(및 유니코드)을 포함한 콘솔 프로그램을 컴파일 및 실행하는 방법
13792정성태10/27/20248663Linux: 99. Linux - 프로세스의 실행 파일 경로 확인
13791정성태10/27/20248764Windows: 267. Win32 API의 A(ANSI) 버전은 DBCS를 사용할까요?파일 다운로드1
13790정성태10/27/20248409Linux: 98. Ubuntu 22.04 - 리눅스 커널 빌드 및 업그레이드
13789정성태10/27/20249904Linux: 97. menuconfig에 CONFIG_DEBUG_INFO_BTF, CONFIG_DEBUG_INFO_BTF_MODULES 옵션이 없는 경우
13788정성태10/26/20247620Linux: 96. eBPF (bpf2go) - fentry, fexit를 이용한 트레이스
13787정성태10/26/202410433개발 환경 구성: 730. github - Linux 커널 repo를 윈도우 환경에서 git clone하는 방법 [1]
13786정성태10/26/20249381Windows: 266. Windows - 대소문자 구분이 가능한 파일 시스템
13785정성태10/23/202410666C/C++: 182. 윈도우가 운영하는 2개의 Code Page [1]파일 다운로드1
13784정성태10/23/20249218Linux: 95. eBPF - kprobe를 이용한 트레이스 [1]
13783정성태10/23/20248935Linux: 94. eBPF - vmlinux.h 헤더 포함하는 방법 (bpf2go에서 사용)
13782정성태10/23/20248247Linux: 93. Ubuntu 22.04 - 커널 이미지로부터 커널 함수 역어셈블
13781정성태10/22/20248964오류 유형: 930. WSL + eBPF: modprobe: FATAL: Module kheaders not found in directory
13780정성태10/22/202410784Linux: 92. WSL 2 - 커널 이미지로부터 커널 함수 역어셈블
13779정성태10/22/20248464개발 환경 구성: 729. WSL 2 - Mariner VM 커널 이미지 업데이트 방법
13778정성태10/21/202411047C/C++: 181. C/C++ - 소스코드 파일의 인코딩, 바이너리 모듈 상태의 인코딩
13777정성태10/20/20249212Windows: 265. Win32 API의 W(유니코드) 버전은 UCS-2일까요? UTF-16 인코딩일까요?
13776정성태10/19/20249987C/C++: 180. C++ - 고수준 FILE I/O 함수에서의 Unicode stream 모드(_O_WTEXT, _O_U16TEXT, _O_U8TEXT)파일 다운로드1
13775정성태10/19/202410823개발 환경 구성: 728. 윈도우 환경의 개발자를 위한 UTF-8 환경 설정
13774정성태10/18/20249677Linux: 91. Container 환경에서 출력하는 eBPF bpf_get_current_pid_tgid의 pid가 존재하지 않는 이유
13773정성태10/18/20248979Linux: 90. pid 네임스페이스 구성으로 본 WSL 2 + docker-desktop
13772정성태10/17/20249811Linux: 89. pid 네임스페이스 구성으로 본 WSL 2 배포본의 계층 관계
1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...