Microsoft MVP성태의 닷넷 이야기
닷넷: 2367. C# - Youtube 동영상 다운로드 (YoutubeExplode 패키지) [링크 복사], [링크+제목 복사],
조회: 395
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... 76  77  78  79  [80]  81  82  83  84  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
12035정성태10/13/201923296개발 환경 구성: 461. C# 8.0의 #nulable 관련 특성을 .NET Framework 프로젝트에서 사용하는 방법 [2]파일 다운로드1
12034정성태10/12/201922453개발 환경 구성: 460. .NET Core 환경에서 (프로젝트가 아닌) C# 코드 파일을 입력으로 컴파일하는 방법 [1]
12033정성태10/11/201927532개발 환경 구성: 459. .NET Framework 프로젝트에서 C# 8.0/9.0 컴파일러를 사용하는 방법
12032정성태10/8/201922579.NET Framework: 865. .NET Core 2.2/3.0 웹 프로젝트를 IIS에서 호스팅(Inproc, out-of-proc)하는 방법 - AspNetCoreModuleV2 소개
12031정성태10/7/201921764오류 유형: 569. Azure Site Extension 업그레이드 시 "System.IO.IOException: There is not enough space on the disk" 예외 발생
12030정성태10/5/201928667.NET Framework: 864. .NET Conf 2019 Korea - "닷넷 17년의 변화 정리 및 닷넷 코어 3.0" 발표 자료 [1]파일 다운로드1
12029정성태9/27/201928204제니퍼 .NET: 29. Jennifersoft provides a trial promotion on its APM solution such as JENNIFER, PHP, and .NET in 2019 and shares the examples of their application.
12028정성태9/26/201924900.NET Framework: 863. C# - Thread.Suspend 호출 시 응용 프로그램 hang 현상을 해결하기 위한 시도파일 다운로드1
12027정성태9/26/201917746오류 유형: 568. Consider app.config remapping of assembly "..." from Version "..." [...] to Version "..." [...] to solve conflict and get rid of warning.
12026정성태9/26/201925650.NET Framework: 862. C# - Active Directory의 LDAP 경로 및 정보 조회
12025정성태9/25/201923788제니퍼 .NET: 28. APM 솔루션 제니퍼, PHP, .NET 무료 사용 프로모션 2019 및 적용 사례 (8) [1]
12024정성태9/20/201925845.NET Framework: 861. HttpClient와 HttpClientHandler의 관계 [2]
12023정성태9/18/201926504.NET Framework: 860. ServicePointManager.DefaultConnectionLimit와 HttpClient의 관계파일 다운로드1
12022정성태9/12/201929042개발 환경 구성: 458. C# 8.0 (Preview) 신규 문법을 위한 개발 환경 구성 [3]
12021정성태9/12/201946625도서: 시작하세요! C# 8.0 프로그래밍 [4]
12020정성태9/11/201929070VC++: 134. SYSTEMTIME 값 기준으로 특정 시간이 지났는지를 판단하는 함수
12019정성태9/11/201922523Linux: 23. .NET Core + 리눅스 환경에서 Environment.CurrentDirectory 접근 시 주의 사항
12018정성태9/11/201921909오류 유형: 567. IIS - Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive. (D:\lowSite4\web.config line 11)
12017정성태9/11/201925789오류 유형: 566. 비주얼 스튜디오 - Failed to register URL "http://localhost:6879/" for site "..." application "/". Error description: Access is denied. (0x80070005)
12016정성태9/5/201924085오류 유형: 565. git fetch - warning: 'C:\ProgramData/Git/config' has a dubious owner: '(unknown)'.
12015정성태9/3/201931954개발 환경 구성: 457. 윈도우 응용 프로그램의 Socket 연결 시 time-out 시간 제어
12014정성태9/3/201924585개발 환경 구성: 456. 명령행에서 AWS, Azure 등의 원격 저장소에 파일 관리하는 방법 - cyberduck/duck 소개
12013정성태8/28/201928270개발 환경 구성: 455. 윈도우에서 (테스트) 인증서 파일 만드는 방법 [3]
12012정성태8/28/201933148.NET Framework: 859. C# - HttpListener를 이용한 HTTPS 통신 방법
12011정성태8/27/201932329사물인터넷: 57. C# - Rapsberry Pi Zero W와 PC 간 Bluetooth 통신 예제 코드파일 다운로드1
12010정성태8/27/201924277VS.NET IDE: 138. VSIX - DTE.ItemOperations.NewFile 메서드에서 템플릿 이름을 다국어로 설정하는 방법
... 76  77  78  79  [80]  81  82  83  84  85  86  87  88  89  90  ...