Microsoft MVP성태의 닷넷 이야기
닷넷: 2367. C# - Youtube 동영상 다운로드 (YoutubeExplode 패키지) [링크 복사], [링크+제목 복사],
조회: 397
글쓴 사람
정성태 (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)
12060정성태11/20/201926956디버깅 기술: 132. windbg/Visual Studio - HeapFree x64의 동작 분석
12059정성태11/20/201925678디버깅 기술: 131. windbg/Visual Studio - HeapFree x86의 동작 분석
12058정성태11/19/201925818디버깅 기술: 130. windbg - CoTaskMemFree/FreeCoTaskMem에서 발생한 덤프 분석 사례
12057정성태11/18/201920815오류 유형: 579. Visual Studio - Memory 창에서 유효한 주소 영역임에도 "Unable to evaluate the expression." 오류 출력
12056정성태11/18/201928422개발 환경 구성: 464. "Microsoft Visual Studio Installer Projects" 프로젝트로 EXE 서명 및 MSI 파일 서명 방법파일 다운로드1
12055정성태11/17/201921786개발 환경 구성: 463. Visual Studio의 Ctrl + Alt + M, 1 (Memory 1) 등의 단축키가 동작하지 않는 경우
12054정성태11/15/201923755.NET Framework: 869. C# - 일부러 GC Heap을 깨뜨려 GC 수행 시 비정상 종료시키는 예제
12053정성태11/15/201923048Windows: 166. 윈도우 10 - 명령행 창(cmd.exe) 속성에 (DotumChe, GulimChe, GungsuhChe 등의) 한글 폰트가 없는 경우
12052정성태11/15/201921928오류 유형: 578. Azure - 일정(schedule)에 등록한 runbook이 1년 후 실행이 안 되는 문제(Reason - The key used is expired.)
12051정성태11/14/201927833개발 환경 구성: 462. 시작하자마자 비정상 종료하는 프로세스의 메모리 덤프 - procdump [1]
12050정성태11/14/201925395Windows: 165. AcLayers의 API 후킹과 FaultTolerantHeap
12049정성태11/13/201925845.NET Framework: 868. (닷넷 프로세스를 대상으로) 디버거 방식이 아닌 CLR Profiler를 이용해 procdump.exe 기능 구현
12048정성태11/12/201925099Windows: 164. GUID 이름의 볼륨에 해당하는 파티션을 찾는 방법
12047정성태11/12/201927186Windows: 163. 안전하게 eject시킨 USB 장치를 물리적인 재연결 없이 다시 인식시키는 방법
12046정성태10/29/201921213오류 유형: 577. windbg - The call to LoadLibrary(...\sos.dll) failed, Win32 error 0n193
12045정성태10/27/201922598오류 유형: 576. mstest.exe 실행 시 "Visual Studio Enterprise is required to execute the test." 오류 - 두 번째 이야기
12044정성태10/27/201921087오류 유형: 575. mstest.exe - System.Resources.MissingSatelliteAssemblyException: The satellite assembly named "Microsoft.VisualStudio.ProductKeyDialog.resources.dll, ..."
12043정성태10/27/201923598오류 유형: 574. Windows 10 설치 시 오류 - 0xC1900101 - 0x4001E
12042정성태10/26/201921399오류 유형: 573. OneDrive 하위에 위치한 Documents, Desktop 폴더에 대한 권한 변경 시 "Unable to display current owner"
12041정성태10/23/201923755오류 유형: 572. mstest.exe - The load test results database could not be opened.
12040정성태10/23/201924744오류 유형: 571. Unhandled Exception: System.Net.Mail.SmtpException: Transaction failed. The server response was: 5.2.0 STOREDRV.Submission.Exception:SendAsDeniedException.MapiExceptionSendAsDenied
12039정성태10/22/201920544스크립트: 16. cmd.exe의 for 문에서는 ERRORLEVEL이 설정되지 않는 문제
12038정성태10/17/201922210오류 유형: 570. SQL Server 2019 RC1 - SQL Client Connectivity SDK 설치 오류
12037정성태10/15/201929696.NET Framework: 867. C# - Encoding.Default 값을 바꿀 수 있을까요?파일 다운로드1
12036정성태10/14/201931830.NET Framework: 866. C# - 고성능이 필요한 환경에서 GC가 발생하지 않는 네이티브 힙 사용파일 다운로드1
12035정성태10/13/201923296개발 환경 구성: 461. C# 8.0의 #nulable 관련 특성을 .NET Framework 프로젝트에서 사용하는 방법 [2]파일 다운로드1
... 76  77  78  [79]  80  81  82  83  84  85  86  87  88  89  90  ...