Microsoft MVP성태의 닷넷 이야기
Phone: 20. C# MAUI - 유튜브 동영상을 MediaElement로 재생하는 방법 [링크 복사], [링크+제목 복사],
조회: 3922
글쓴 사람
정성태 (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)
13778정성태10/21/2024182C/C++: 181. C/C++ - 소스코드 파일의 인코딩, 바이너리 모듈 상태의 인코딩
13777정성태10/20/2024163Windows: 265. Win32 API의 W(유니코드) 버전은 UCS-2일까요? UTF-16 인코딩일까요?
13776정성태10/19/2024406C/C++: 180. C++ - 고수준 FILE I/O 함수에서의 Unicode stream 모드(_O_WTEXT, _O_U16TEXT, _O_U8TEXT)파일 다운로드1
13775정성태10/19/2024360개발 환경 구성: 728. 윈도우 환경의 개발자를 위한 UTF-8 환경 설정
13774정성태10/18/2024575Linux: 91. Container 환경에서 출력하는 eBPF bpf_get_current_pid_tgid의 pid가 존재하지 않는 이유
13773정성태10/18/2024331Linux: 90. pid 네임스페이스 구성으로 본 WSL 2 + docker-desktop
13772정성태10/17/2024501Linux: 89. pid 네임스페이스 구성으로 본 WSL 2 배포본의 계층 관계
13771정성태10/17/2024709Linux: 88. WSL 2 리눅스 배포본 내에서의 pid 네임스페이스 구성
13770정성태10/17/2024573Linux: 87. ps + grep 조합에서 grep 명령어를 사용한 프로세스를 출력에서 제거하는 방법
13769정성태10/15/2024591Linux: 86. Golang + bpf2go를 사용한 eBPF 기본 예제파일 다운로드1
13768정성태10/15/2024613C/C++: 179. C++ - _O_WTEXT, _O_U16TEXT, _O_U8TEXT의 Unicode stream 모드파일 다운로드2
13767정성태10/14/2024595오류 유형: 929. bpftrace 수행 시 "ERROR: Could not resolve symbol: /proc/self/exe:BEGIN_trigger"
13766정성태10/14/2024692C/C++: 178. C++ - 파일에 대한 Text 모드의 "translated" 동작파일 다운로드1
13765정성태10/12/2024761오류 유형: 928. go build 시 "package maps is not in GOROOT" 오류
13764정성태10/11/2024714Linux: 85. Ubuntu - 원하는 golang 버전 설치
13763정성태10/11/2024757Linux: 84. WSL / Ubuntu 20.04 - bpftool 설치
13762정성태10/11/2024799Linux: 83. WSL / Ubuntu 22.04 - bpftool 설치
13761정성태10/11/2024734오류 유형: 927. WSL / Ubuntu - /usr/include/linux/types.h:5:10: fatal error: 'asm/types.h' file not found
13760정성태10/11/2024748Linux: 82. Ubuntu - clang 최신(stable) 버전 설치
13759정성태10/10/20241075C/C++: 177. C++ - 자유 함수(free function) 및 주소 지정 가능한 함수(addressable function) [6]
13758정성태10/8/2024928오류 유형: 926. dotnet tools를 sudo로 실행하는 경우 command not found
13757정성태10/8/2024883닷넷: 2306. Linux - dotnet tool의 설치 디렉터리가 PATH 환경변수에 자동 등록이 되는 이유
13756정성태10/8/2024883오류 유형: 925. ssh로 docker 접근을 할 때 "... malformed HTTP status code ..." 오류 발생
13755정성태10/7/20241059닷넷: 2305. C# 13 - (9) 메서드 바인딩의 우선순위를 지정하는 OverloadResolutionPriority 특성 도입 (Overload resolution priority)파일 다운로드1
13754정성태10/4/2024924닷넷: 2304. C# 13 - (8) 부분 메서드 정의를 속성 및 인덱서에도 확대파일 다운로드1
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...