Microsoft MVP성태의 닷넷 이야기
Phone: 20. C# MAUI - 유튜브 동영상을 MediaElement로 재생하는 방법 [링크 복사], [링크+제목 복사],
조회: 6247
글쓴 사람
정성태 (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)
13671정성태7/10/20244857오류 유형: 914. Package ca-certificates is not installed.
13669정성태7/9/20245153오류 유형: 913. C# - AOT StaticExecutable 정적 링킹 시 빌드 오류
13668정성태7/8/20244977개발 환경 구성: 716. Hyper-V - Ubuntu 22.04 Generation 2 유형의 VM 설치
13667정성태7/7/20244491닷넷: 2273. C# - 리눅스 환경에서의 Hyper-V Socket 연동 (AF_VSOCK)파일 다운로드1
13666정성태7/7/20245297Linux: 74. C++ - Vsock 예제 (Hyper-V Socket 연동)파일 다운로드1
13665정성태7/6/20245321Linux: 73. Linux 측의 socat을 이용한 Hyper-V 호스트와의 vsock 테스트파일 다운로드1
13663정성태7/5/20245249닷넷: 2272. C# - Hyper-V Socket 통신(AF_HYPERV, AF_VSOCK)의 VMID Wildcards 유형파일 다운로드1
13662정성태7/4/20245736닷넷: 2271. C# - WSL 2 VM의 VM ID를 알아내는 방법 - Host Compute System API파일 다운로드1
13661정성태7/3/20245407Linux: 72. g++ - 다른 버전의 GLIBC로 소스코드 빌드
13660정성태7/3/20245056오류 유형: 912. Visual C++ - Linux 프로젝트 빌드 오류
13659정성태7/1/20245333개발 환경 구성: 715. Windows - WSL 2 환경의 Docker Desktop 네트워크
13658정성태6/28/20245272개발 환경 구성: 714. WSL 2 인스턴스와 호스트 측의 Hyper-V에 운영 중인 VM과 네트워크 연결을 하는 방법 - 두 번째 이야기
13657정성태6/27/20245701닷넷: 2270. C# - Hyper-V Socket 통신(AF_HYPERV, AF_VSOCK)을 위한 EndPoint 사용자 정의
13656정성태6/27/20245195Windows: 264. WSL 2 VM의 swap 파일 위치
13655정성태6/24/20245353닷넷: 2269. C# - Win32 Resource 포맷 해석파일 다운로드1
13654정성태6/24/20245192오류 유형: 911. shutdown - The entered computer name is not valid or remote shutdown is not supported on the target computer.
13653정성태6/22/20245540닷넷: 2268. C# 코드에서 MAKEINTREOURCE 매크로 처리
13652정성태6/21/20246190닷넷: 2267. C# - Linux 환경에서 (Reflection 없이) DLL AssemblyFileVersion 구하는 방법파일 다운로드2
13651정성태6/19/20245864닷넷: 2266. C# - (Reflection 없이) DLL AssemblyFileVersion 구하는 방법파일 다운로드1
13650정성태6/18/20245735개발 환경 구성: 713. "WSL --debug-shell"로 살펴보는 WSL 2 VM의 리눅스 환경
13649정성태6/18/20245525오류 유형: 910. windbg - !py 확장 명령어 실행 시 "failed to find python interpreter" (2)
13648정성태6/17/20245311오류 유형: 909. C# - DynamicMethod 사용 시 System.TypeAccessException
13647정성태6/16/20245967개발 환경 구성: 712. Windows - WSL 2의 네트워크 통신 방법 - 세 번째 이야기 (같은 IP를 공유하는 WSL 2 인스턴스) [1]
13646정성태6/14/20245056오류 유형: 908. Process Explorer - "Error configuring dump resources: The system cannot find the file specified."
13645정성태6/13/20245601개발 환경 구성: 711. Visual Studio로 개발 시 기본 등록하는 dev tag 이미지로 Docker Desktop k8s에서 실행하는 방법
13644정성태6/12/20246157닷넷: 2265. C# - System.Text.Json의 기본적인 (한글 등에서의) escape 처리 [1]
1  2  3  4  5  6  7  8  [9]  10  11  12  13  14  15  ...