Microsoft MVP성태의 닷넷 이야기
Phone: 20. C# MAUI - 유튜브 동영상을 MediaElement로 재생하는 방법 [링크 복사], [링크+제목 복사],
조회: 6942
글쓴 사람
정성태 (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)
13657정성태6/27/20246430닷넷: 2270. C# - Hyper-V Socket 통신(AF_HYPERV, AF_VSOCK)을 위한 EndPoint 사용자 정의
13656정성태6/27/20245875Windows: 264. WSL 2 VM의 swap 파일 위치
13655정성태6/24/20246046닷넷: 2269. C# - Win32 Resource 포맷 해석파일 다운로드1
13654정성태6/24/20245991오류 유형: 911. shutdown - The entered computer name is not valid or remote shutdown is not supported on the target computer.
13653정성태6/22/20246217닷넷: 2268. C# 코드에서 MAKEINTREOURCE 매크로 처리
13652정성태6/21/20246797닷넷: 2267. C# - Linux 환경에서 (Reflection 없이) DLL AssemblyFileVersion 구하는 방법파일 다운로드2
13651정성태6/19/20246374닷넷: 2266. C# - (Reflection 없이) DLL AssemblyFileVersion 구하는 방법파일 다운로드1
13650정성태6/18/20246223개발 환경 구성: 713. "WSL --debug-shell"로 살펴보는 WSL 2 VM의 리눅스 환경
13649정성태6/18/20246136오류 유형: 910. windbg - !py 확장 명령어 실행 시 "failed to find python interpreter" (2)
13648정성태6/17/20246036오류 유형: 909. C# - DynamicMethod 사용 시 System.TypeAccessException
13647정성태6/16/20246746개발 환경 구성: 712. Windows - WSL 2의 네트워크 통신 방법 - 세 번째 이야기 (같은 IP를 공유하는 WSL 2 인스턴스) [1]
13646정성태6/14/20245659오류 유형: 908. Process Explorer - "Error configuring dump resources: The system cannot find the file specified."
13645정성태6/13/20246353개발 환경 구성: 711. Visual Studio로 개발 시 기본 등록하는 dev tag 이미지로 Docker Desktop k8s에서 실행하는 방법
13644정성태6/12/20246751닷넷: 2265. C# - System.Text.Json의 기본적인 (한글 등에서의) escape 처리 [1]
13643정성태6/12/20246487오류 유형: 907. MySqlConnector 사용 시 System.IO.FileLoadException 오류
13642정성태6/11/20246591스크립트: 65. 파이썬 - asgi 버전(2, 3)에 따라 달라지는 uvicorn 호스팅
13641정성태6/11/20246483Linux: 71. Ubuntu 20.04를 22.04로 업데이트
13640정성태6/10/20246746Phone: 21. C# MAUI - Android 환경에서의 파일 다운로드(DownloadManager)
13639정성태6/8/20246417오류 유형: 906. C# MAUI - Android Emulator에서 "Waiting For Debugger"로 무한 대기
13638정성태6/8/20246743오류 유형: 905. C# MAUI - 추가한 layout XML 파일이 Resource.Layout 멤버로 나오지 않는 문제
13637정성태6/6/20246942Phone: 20. C# MAUI - 유튜브 동영상을 MediaElement로 재생하는 방법
13636정성태5/30/20246772닷넷: 2264. C# - 형식 인자로 인터페이스를 갖는 제네릭 타입으로의 형변환파일 다운로드1
13635정성태5/29/20247096Phone: 19. C# MAUI - 안드로이드 "Share" 대상으로 등록하는 방법
13634정성태5/24/20247343Phone: 18. C# MAUI - 안드로이드 플랫폼에서의 Activity 제어 [1]
13633정성태5/22/20246840스크립트: 64. 파이썬 - ASGI를 만족하는 최소한의 구현 코드
13632정성태5/20/20247052Phone: 17. C# MAUI - Android 내에 Web 서비스 호스팅
1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...