Microsoft MVP성태의 닷넷 이야기
Phone: 20. C# MAUI - 유튜브 동영상을 MediaElement로 재생하는 방법 [링크 복사], [링크+제목 복사],
조회: 6351
글쓴 사람
정성태 (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)
13877정성태1/25/2025215닷넷: 2315. C# - PCI 장치 열거 (레지스트리, SetupAPI)파일 다운로드1
13876정성태1/25/2025261닷넷: 2314. C# - ProcessStartInfo 타입의 Arguments와 ArgumentList파일 다운로드1
13875정성태1/24/2025267스크립트: 69. 파이썬 - multiprocessing 패키지의 spawn 모드로 동작하는 uvicorn의 workers
13874정성태1/24/2025279스크립트: 68. 파이썬 - multiprocessing Pool의 기본 프로세스 시작 모드(spawn, fork)
13873정성태1/23/2025334디버깅 기술: 217. WinDbg - PCI 장치 열거
13872정성태1/23/2025303오류 유형: 944. WinDbg - 원격 커널 디버깅이 연결은 되지만 Break (Ctrl + Break) 키를 눌러도 멈추지 않는 현상
13871정성태1/22/2025463Windows: 278. Windows - 윈도우를 다른 모니터 화면으로 이동시키는 단축키 (Window + Shift + 화살표)
13870정성태1/18/2025811개발 환경 구성: 741. WinDbg - 네트워크 커널 디버깅이 가능한 NIC 카드 지원 확대
13869정성태1/18/2025790개발 환경 구성: 740. WinDbg - _NT_SYMBOL_PATH 환경 변수에 설정한 경로로 심벌 파일을 다운로드하지 않는 경우
13868정성태1/17/2025879Windows: 277. Hyper-V - Windows 11 VM의 Enhanced Session 모드로 로그인을 할 수 없는 문제
13867정성태1/17/2025976오류 유형: 943. Hyper-V에 Windows 11 설치 시 "This PC doesn't currently meet Windows 11 system requirements" 오류
13866정성태1/16/20251100개발 환경 구성: 739. Windows 10부터 바뀐 device driver 서명 방법
13865정성태1/15/20251073오류 유형: 942. C# - .NET Framework 4.5.2 이하의 버전에서 HttpWebRequest로 https 호출 시 "System.Net.WebException" 예외 발생
13864정성태1/15/20251052Linux: 114. eBPF를 위해 필요한 SELinux 보안 정책
13863정성태1/14/20251117Linux: 113. Linux - 프로세스를 위한 전용 SELinux 보안 문맥 지정
13862정성태1/13/20251049Linux: 112. Linux - 데몬을 위한 SELinux 보안 정책 설정
13861정성태1/11/20251144Windows: 276. 명령행에서 원격 서비스를 동기/비동기로 시작/중지
13860정성태1/10/20251089디버깅 기술: 216. WinDbg - 2가지 유형의 식 평가 방법(MASM, C++)
13859정성태1/9/20251090디버깅 기술: 215. Windbg - syscall 이후 실행되는 KiSystemCall64 함수 및 SSDT 디버깅
13858정성태1/8/20251221개발 환경 구성: 738. PowerShell - 원격 호출 시 "powershell.exe"가 아닌 "pwsh.exe" 환경으로 명령어를 실행하는 방법
13857정성태1/7/20251162C/C++: 187. Golang - 콘솔 응용 프로그램을 Linux 데몬 서비스를 지원하도록 변경파일 다운로드1
13856정성태1/6/20251122디버깅 기술: 214. Windbg - syscall 단계까지의 Win32 API 호출 (예: Sleep)
13855정성태12/28/20241565오류 유형: 941. Golang - os.StartProcess() 사용 시 오류 정리
13854정성태12/27/20241622C/C++: 186. Golang - 콘솔 응용 프로그램을 NT 서비스를 지원하도록 변경파일 다운로드1
13853정성태12/26/20241887디버깅 기술: 213. Windbg - swapgs 명령어와 (Ring 0 커널 모드의) FS, GS Segment 레지스터
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...