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

비밀번호

댓글 작성자
 




... 46  47  48  49  50  51  52  [53]  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12714정성태7/16/202119341오류 유형: 735. VCRUNTIME140.dll, MSVCP140.dll, VCRUNTIME140.dll, VCRUNTIME140_1.dll이 없어 exe 실행이 안 되는 경우
12713정성태7/16/202122202.NET Framework: 1077. C# - 동기 방식이면서 비동기 규약을 따르게 만드는 Task.FromResult파일 다운로드1
12712정성태7/15/202120571개발 환경 구성: 579. Azure - 리눅스 호스팅의 Site Extension 제작 방법
12711정성태7/15/202119308개발 환경 구성: 578. Azure - Java Web App Service를 위한 Site Extension 제작 방법
12710정성태7/15/202124375개발 환경 구성: 577. MQTT - emqx.io 서비스 소개
12709정성태7/14/202119235Linux: 42. 실행 중인 docker 컨테이너에 대한 구동 시점의 docker run 명령어를 확인하는 방법
12708정성태7/14/202124141Linux: 41. 리눅스 환경에서 디스크 용량 부족 시 원인 분석 방법
12707정성태7/14/202189243오류 유형: 734. MySQL - Authentication method 'caching_sha2_password' not supported by any of the available plugins.
12706정성태7/14/202121112.NET Framework: 1076. C# - AsyncLocal 기능을 CallContext만으로 구현하는 방법 [2]파일 다운로드1
12705정성태7/13/202121977VS.NET IDE: 168. x64 DLL 프로젝트의 컨트롤이 Visual Studio의 Designer에서 보이지 않는 문제 - 두 번째 이야기
12704정성태7/12/202120010개발 환경 구성: 576. Azure VM의 서비스를 Azure Web App Service에서만 접근하도록 NSG 설정을 제한하는 방법
12703정성태7/11/202124498개발 환경 구성: 575. Azure VM에 (ICMP) ping을 허용하는 방법
12702정성태7/11/202121922오류 유형: 733. TaskScheduler에 등록된 wacs.exe의 Let's Encrypt 인증서 업데이트 문제
12701정성태7/9/202121926.NET Framework: 1075. C# - ThreadPool의 스레드는 반환 시 ThreadStatic과 AsyncLocal 값이 초기화 될까요?파일 다운로드1
12700정성태7/8/202122226.NET Framework: 1074. RuntimeType의 메모리 누수? [1]
12699정성태7/8/202121255VS.NET IDE: 167. Visual Studio 디버깅 중 GC Heap 상태를 보여주는 "Show Diagnostic Tools" 메뉴 사용법
12698정성태7/7/202124879오류 유형: 732. Windows 11 업데이트 시 3% 또는 0%에서 다운로드가 멈춘 경우
12697정성태7/7/202118766개발 환경 구성: 574. Windows 11 (Insider Preview) 설치하는 방법
12696정성태7/6/202121023VC++: 146. 운영체제의 스레드 문맥 교환(Context Switch)을 유사하게 구현하는 방법파일 다운로드2
12695정성태7/3/202121087VC++: 145. C 언어의 setjmp/longjmp 기능을 Thread Context를 이용해 유사하게 구현하는 방법파일 다운로드1
12694정성태7/2/202122859Java: 24. Azure - Spring Boot 앱을 Java SE(Embedded Web Server)로 호스팅 시 로그 파일 남기는 방법 [1]
12693정성태6/30/202118982오류 유형: 731. Azure Web App Site Extension - Failed to install web app extension [...]. {1}
12692정성태6/30/202120455디버깅 기술: 180. Azure - Web App의 비정상 종료 시 남겨지는 로그 확인
12691정성태6/30/202119857개발 환경 구성: 573. 테스트 용도이지만 테스트에 적합하지 않은 Azure D1 공유(shared) 요금제
12690정성태6/28/202120419Java: 23. Azure - 자바(Java)로 만드는 Web App Service - Tomcat 호스팅
12689정성태6/25/202123830오류 유형: 730. Windows Forms 디자이너 - The class Form1 can be designed, but is not the first class in the file. [1]
... 46  47  48  49  50  51  52  [53]  54  55  56  57  58  59  60  ...