Microsoft MVP성태의 닷넷 이야기
닷넷: 2367. C# - Youtube 동영상 다운로드 (YoutubeExplode 패키지) [링크 복사], [링크+제목 복사],
조회: 118
글쓴 사람
정성태 (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)
14021정성태10/6/2025118닷넷: 2367. C# - Youtube 동영상 다운로드 (YoutubeExplode 패키지)파일 다운로드1
14020정성태10/2/20251247Linux: 125. eBPF - __attribute__((preserve_access_index)) 활용 사례
14019정성태10/1/20251179Linux: 124. eBPF - __sk_buff / sk_buff 구조체
14018정성태9/30/2025792닷넷: 2366. C# - UIAutomationClient를 이용해 시스템 트레이의 아이콘을 열거하는 방법파일 다운로드1
14017정성태9/29/20251587Linux: 123. eBPF (bpf2go) - BPF_PROG_TYPE_SOCKET_FILTER 예제 - SEC("socket")
14016정성태9/28/20251710Linux: 122. eBPF - __attribute__((preserve_access_index)) 사용법
14015정성태9/22/20251509닷넷: 2365. C# - FFMpegCore를 이용한 MP4 동영상으로부터 MP3 음원 추출 예제파일 다운로드1
14014정성태9/17/20251556닷넷: 2364. C# - stun.l.google.com을 사용해 공용 IP 주소와 포트를 알아내는 방법파일 다운로드1
14013정성태9/14/20252218닷넷: 2363. C# - Whisper.NET Library를 이용해 음성을 텍스트로 변환 및 번역하는 예제파일 다운로드1
14012정성태9/9/20252328닷넷: 2362. C# - Windows.Media.Ocr: 윈도우 운영체제에 포함된 OCR(Optical Character Recognition)파일 다운로드1
14011정성태9/7/20252638닷넷: 2361. C# - Linux 환경의 readlink 호출
14010정성태9/1/20252623오류 유형: 983. apt update 시 "The repository 'http://deb.debian.org/debian buster Release' does not have a Release file." 오류
14009정성태8/28/20253306닷넷: 2360. C# 14 - (11) Expression Tree에 선택적 인수와 명명된 인수 허용파일 다운로드1
14008정성태8/26/20253684닷넷: 2359. C# 14 - (10) 복합 대입 연산자의 오버로드 지원파일 다운로드1
14007정성태8/25/20254008닷넷: 2358. C# - 현재 빌드에 적용 중인 컴파일러 버전 확인 방법 (#error version)
14006정성태8/23/20254259Linux: 121. Linux - snap 패키지 관리자로 설치한 소프트웨어의 디렉터리 접근 제한
14005정성태8/21/20253568오류 유형: 982. sudo: unable to load /usr/libexec/sudo/sudoers.so: libssl.so.3: cannot open shared object file: No such file or directory
14004정성태8/21/20254128오류 유형: 981. dotnet 실행 시 No usable version of the libssl was found
14003정성태8/21/20254270닷넷: 2357. C# 14 - (9) 새로운 지시자 추가 (Ignored directives)
14002정성태8/20/20254577오류 유형: 980. C# - appsettings.json 파일의 설정값이 적용 안 된다면?
14001정성태8/19/20259367닷넷: 2356. .NET SDK 10 - 단일 소스 코드 파일을 빌드/실행하는 기능을 "dotnet" 명령어에 추가 [1]
14000정성태8/18/20254789오류 유형: 979. ERROR: failed to solve: failed to read dockerfile: open Dockerfile: no such file or directory
13999정성태8/15/20254406닷넷: 2355. C# 14 - (8) null 조건부 연산자 개선 - 대입문에도 사용 가능파일 다운로드1
13998정성태8/14/20254001닷넷: 2354. C# 14 - (7) 확장 메서드에 정적 메서드와 속성 지원을 위한 전용 구문 추가파일 다운로드1
13997정성태8/14/20254712Linux: 120. docker 컨테이너로 매핑된 볼륨에 컨테이너 측의 사용자 ID를 유지하면서 복사하는 방법
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...