Microsoft MVP성태의 닷넷 이야기
Phone: 20. C# MAUI - 유튜브 동영상을 MediaElement로 재생하는 방법 [링크 복사], [링크+제목 복사],
조회: 8444
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
 
(연관된 글이 3개 있습니다.)

C# MAUI - 유튜브 동영상을 MediaElement로 재생하는 방법

지난 글까지 해서,

C# MAUI - 안드로이드 "Share" 대상으로 등록하는 방법
; https://www.sysnet.pe.kr/2/0/13635

유튜브로부터 동영상 URL을 전달받는 것까지 완료를 했습니다. 그렇다면 이제 그 URL에 해당하는 영상을 MediaElement로 볼 수 있으면 좋을 텐데요, 아쉽게도 여기에는 한 가지 문제가 있습니다.

다들 아시는 것처럼, Youtube의 동영상에서 "Copy video URL" 메뉴로 복사한 링크는, 예를 들어 "https://youtu.be/GPAe6d_NE8E" 이런 형식인데요, 이건 "동영상을 포함한 유튜브 페이지"의 URL입니다. 그래서 그 URL을 직접 MediaElement의 Source에 지정할 수는 없습니다.

다행히도 이런 문제(?)를 해결하려는 사용자들의 시도가 youtube-dl같은 도구로 있었는데요,

유튜브(youtube) 동영상을 다운로드하는 프로그램 youtube-dl 소개
; https://www.sysnet.pe.kr/0/0/488

youtube-dl을 파이썬으로 실행하는 방법
; https://www.sysnet.pe.kr/0/0/549

물론 C#으로도 YoutubeExplode 등의 라이브러리를 이용해 쉽게 구현할 수 있습니다.

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

따라서 해당 패키지를 참조 추가하고,

Install-Package YoutubeExplode

다음과 같이 코드를 사용하면, 동영상의 진짜 URL, 즉 다운로드 가능한 URL을 구할 수 있습니다.

using System.Xml;
using YoutubeExplode;
using YoutubeExplode.Videos.Streams;

namespace ConsoleApp1;

internal class Program
{
    // Install-Package YoutubeExplode
    static async Task Main(string[] args)
    {
        string url = await GetLink("https://youtu.be/GPAe6d_NE8E");
        Console.WriteLine(url);
    }

    private static async Task<string> GetLink(string url)
    {
        var youtube = new YoutubeClient();

        var streamManifest = await youtube.Videos.Streams.GetManifestAsync(url);
        var streamInfo = streamManifest.GetMuxedStreams()
            .Where(s => s.Container == Container.Mp4)
            .GetWithHighestVideoQuality();

        return streamInfo.Url
    }
}

실행하면 이런 식의 아주 복잡한 URL이 나오는데,

https://rr4---sn-3u-bh2zz.googlevideo.com/videoplayback?expire=1716988995&ei=49dWZtG9KdCQs8IP1fmK2Aw&ip=59.7.103.152&id=o-AOuGI1vXV3-aM3P5bYsMNTYEa4e6St4FtPXiVfiu1Co5&itag=18&source=youtube&requiressl=yes&xpc=EgVo2aDSNQ%3D%3D&mh=H4&mm=31%2C26&mn=sn-3u-bh2zz%2Csn-oguesnds&ms=au%2Conr&mv=m&mvi=4&pl=17&initcwndbps=706250&vprv=1&svpuc=1&mime=video%2Fmp4&rqh=1&gir=yes&clen=12009656&ratebypass=yes&dur=265.218&lmt=1387758073146630&mt=1716967012&fvip=2&c=ANDROID_TESTSUITE&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cxpc%2Cvprv%2Csvpuc%2Cmime%2Crqh%2Cgir%2Cclen%2Cratebypass%2Cdur%2Clmt&sig=AJf...[생략]...7aAw%3D%3D&lsparams=mh%2Cmm%2Cmn%2Cms%2Cmv%2Cmvi%2Cpl%2Cinitcwndbps&lsig=AH...[생략]...AExg%3D%3D


expire가 있으니, 아마도 cache한 저 URL이 영구적이지 않음을 예상케 합니다. 일단 저렇게 실제 동영상의 URL을 구했으면 이후에는 일반적인 절차로 HTTP 통신을 이용한 다운로드를 할 수 있습니다. ^^

WebClient wc = new WebClient();
byte [] contents = wc.DownloadData(streamInfo.Url);
File.WriteAllBytes(@"C:\temp\test.mp4", contents);

이외에도 유튜브 자료의 Video 또는 Audio만 선택해서 다운로드하는 방법 등 다양한 활용이 있는데요, 그런 예제 코드는 github README에 모두 상세하게 설명하고 있으니 참고하시고.




자, 그럼 이것을 지난 예제에 곁들이면 WeakReferenceMessenger에서 대충 이렇게 처리할 수 있을 텐데,

WeakReferenceMessenger.Default.Register<UrlShareMessage>(this, async (r, m) =>
{
    var urlText = m.Value;
    this.Title = urlText;

    var youtube = new YoutubeClient();

    var streamManifest = await youtube.Videos.Streams.GetManifestAsync(urlText);
    var streamInfo = streamManifest.GetMuxedStreams()
        .Where(s => s.Container == Container.Mp4)
        .GetWithHighestVideoQuality();

    this.mediaPlayer.Source = streamInfo.Url;
});

아쉽게도 저렇게 하면 Android.OS.NetworkOnMainThreadException 예외가 발생합니다. 그런데 예외 이름이 좀 특이하죠? ^^ 메인 스레드에서 Network 통신을 하고 있어서 예외를 발생시킨다는 의미인데, 스마트폰에서의 앱이 UI 반응을 할 수 없도록 만드는 상황을 강제로 막은 것이라고 보면 됩니다. (예전에 윈도우의 경우 Store App에서는 동기 호출을 모두 없앤 정책과 유사합니다.)

따라서, 이것을 정상 동작하게 만들려면 일단 별도의 스레드로 빼야 합니다.

await Task.Run(async() =>
{
    var streamManifest = await youtube.Videos.Streams.GetManifestAsync(urlText);

    var streamInfo = streamManifest.GetMuxedStreams()
        .Where(s => s.Container == Container.Mp4)
        .GetWithHighestVideoQuality();
    
    this.mediaPlayer.Source = streamInfo.Url;
});

하지만, 그렇게 되면 mediaPlayer UI 요소에 접근하는 스레드가 Main 스레드가 아니므로 "this.mediaPlayer.Source = streamInfo.Url;" 코드에서 다시 이런 예외가 발생합니다.

Java.Lang.IllegalStateException: 'Player is accessed on the wrong thread.
Current thread: 'Thread-12'
Expected thread: 'main'
See https://developer.android.com/guide/topics/media/issues/player-accessed-on-wrong-thread'

따라서 최종적으로는 이렇게 코드가 나와야 합니다. ^^

WeakReferenceMessenger.Default.Register<UrlShareMessage>(this, async (r, m) =>
{
    var urlText = m.Value;
    this.Title = urlText;

    var youtube = new YoutubeClient();

    await Task.Run(async() =>
    {
        var streamManifest = await youtube.Videos.Streams.GetManifestAsync(urlText);

        var streamInfo = streamManifest.GetMuxedStreams()
            .Where(s => s.Container == Container.Mp4)
            .GetWithHighestVideoQuality();

        await MainThread.InvokeOnMainThreadAsync(() =>
        {
            this.mediaPlayer.Source = streamInfo.Url;
        });                
    });
});

어쨌든, 위의 코드까지 완료하고 실행하면 ^^ 이제 정상적으로 MediaElement에서 Youtube 동영상을 재생할 수 있습니다.




Whisper API Python 사용법
; https://wooiljeong.github.io/python/whisper-api/




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 9/26/2024]

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)
13591정성태4/2/20249429닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20249221Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20249605닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/202410660닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20249538오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/202412384Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/202410100Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/202411671개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법 [9]파일 다운로드1
13583정성태3/25/20249699Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/202410816Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/202410477개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20249461닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/202410410오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/202411145닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/202411077닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
13576정성태3/8/202410344닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
13575정성태3/7/202410803닷넷: 2227. 최신 C# 문법을 .NET Framework 프로젝트에 쓸 수 있을까요?
13574정성태3/6/202410283닷넷: 2226. C# - "Docker Desktop for Windows" Container 환경에서의 IPv6 DualMode 소켓
13573정성태3/5/20249467닷넷: 2225. Windbg - dumasync로 분석하는 async/await 호출
13572정성태3/4/20249470닷넷: 2224. C# - WPF의 Dispatcher Queue로 알아보는 await 호출의 hang 현상파일 다운로드1
13571정성태3/1/20249434닷넷: 2223. C# - await 호출과 WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13570정성태2/29/202410077닷넷: 2222. C# - WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13569정성태2/28/202410180닷넷: 2221. C# - LoadContext, LoadFromContext 그리고 GAC파일 다운로드1
13568정성태2/27/20249719닷넷: 2220. C# - .NET Framework 프로세스의 LoaderOptimization 설정을 확인하는 방법파일 다운로드1
13567정성태2/27/20249635오류 유형: 898. .NET Framework 3.5 이하에서 mscoree.tlb 참조 시 System.BadImageFormatException파일 다운로드1
13566정성태2/27/20249543오류 유형: 897. Windows 7 SDK 설치 시 ".NET Development" 옵션이 비활성으로 선택이 안 되는 경우
1  2  3  4  5  6  7  8  9  10  11  12  13  [14]  15  ...