Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

(시리즈 글이 10개 있습니다.)
.NET Framework: 388. 일반 닷넷 프로젝트에서 WinRT API를 호출하는 방법
; https://www.sysnet.pe.kr/2/0/1508

.NET Framework: 613. 윈도우 데스크톱 응용 프로그램(예: Console)에서 알림 메시지(Toast notifications) 띄우기
; https://www.sysnet.pe.kr/2/0/11073

.NET Framework: 623. C# - PeerFinder를 이용한 Wi-Fi Direct 데이터 통신 예제
; https://www.sysnet.pe.kr/2/0/11106

.NET Framework: 678. 데스크톱 윈도우 응용 프로그램에서 UWP 라이브러리를 이용한 비디오 장치 열람하는 방법
; https://www.sysnet.pe.kr/2/0/11284

.NET Framework: 715. C# - Windows 10 운영체제의 데스크톱 앱에서 TTS(SpeechSynthesizer) 사용하는 방법
; https://www.sysnet.pe.kr/2/0/11412

.NET Framework: 722. C# - Windows 10 운영체제의 데스크톱 앱에서 음성인식(SpeechRecognizer) 사용하는 방법
; https://www.sysnet.pe.kr/2/0/11420

.NET Framework: 804. WPF(또는 WinForm)에서 UWP UI 구성 요소 사용하는 방법
; https://www.sysnet.pe.kr/2/0/11799

.NET Framework: 852. WPF/WinForm에서 UWP의 기능을 이용해 Bluetooth 기기와 Pairing하는 방법
; https://www.sysnet.pe.kr/2/0/12001

.NET Framework: 991. .NET 5 응용 프로그램에서 WinRT API 호출
; https://www.sysnet.pe.kr/2/0/12470

닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
; https://www.sysnet.pe.kr/2/0/13438




C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어

비록 UWP는 수명을 다했지만, Win32의 후속으로 나온 WinRT는 (WinUI 3 프로젝트에서도 사용하게 되면서) 살아남고 있는데요, 간혹 Raymond Chen의 블로그를 보면 심심치 않게 WinRT를, 그것도 C++/WinRT 응용 프로그램을 만드는 것을 볼 수 있습니다.

이번 글도 마찬가지인데요,

How can I get information about media playing on the system, and optionally control their playback?
; https://devblogs.microsoft.com/oldnewthing/20231108-00/?p=108980

친절하게도 (C++와 함께) C# 소스 코드까지 실어 소개하고 있습니다.

using Windows.ApplicationModel;
using Windows.Media.Control;

class Program
{
    static string DisplayNameFromAppId(string appid)
    {
        try
        {
            return AppInfo.GetFromAppUserModelId(appid).DisplayInfo.DisplayName;
        }
        catch (Exception)
        {
            return appid;
        }
    }


    static async Task Run()
    {
        var manager =
            await GlobalSystemMediaTransportControlsSessionManager.RequestAsync();
        var current = manager.GetCurrentSession();
        if (current != null)
        {
            Console.WriteLine("Current media app: " +
                              DisplayNameFromAppId(current.SourceAppUserModelId));
        }
        foreach (var session in manager.GetSessions())
        {
            Console.WriteLine("Session from: " +
                              DisplayNameFromAppId(session.SourceAppUserModelId));

            var timelineProperties = session.GetTimelineProperties();
            Console.WriteLine($"\tPosition: {timelineProperties.Position}");
            Console.WriteLine($"\tStart: {timelineProperties.StartTime}");
            Console.WriteLine($"\tEnd: {timelineProperties.EndTime}");

            var info = session.GetPlaybackInfo();
            var rate = info.PlaybackRate;
            if (rate != null)
            {
                Console.WriteLine($"\tPlayback speed: {rate.Value}");
            }

            var controls = info.Controls;
            Console.WriteLine($"\tCan pause: {controls.IsPauseEnabled}");

            if (info.PlaybackStatus ==
                GlobalSystemMediaTransportControlsSessionPlaybackStatus.Playing &&
                controls.IsPauseEnabled)
            {
                await session.TryPauseAsync();
            }
        }
    }

    [MTAThread]
    public static void Main()
    {
        Run().Wait();
    }
}

사용법이 매우 단순한데요, GlobalSystemMediaTransportControlsSessionManager를 구한 후 Session을 열거하는 것으로, 현재 시스템에 실행 중인 다양한 Media 재생기를 제어하고 있습니다.

실제로, 제 컴퓨터에서 윈도우에 기본 포함된 "Media Player"로 mp3 음악을 재생하면서 동시에 Edge 브라우저를 실행해 유튜브 영상을 틀은 상태로 저 코드를 실행했더니 다음과 같은 출력 결과가 나오고,

Current media app: Media Player
Session from: Media Player
        Position: 00:00:47.3734145
        Start: 00:00:00
        End: 00:05:28.1916666
        Playback speed: 1
        Can pause: True
Session from: MSEdge
        Position: 00:00:00.0424370
        Start: 00:00:00
        End: 00:01:59.4210000
        Playback speed: 1
        Can pause: True

"await session.TryPauseAsync();" 코드의 수행에 따라 재생하는 것을 모두 멈췄습니다.

아마도, 저 과정을 단순히 Win32 API를 이용해 만들어야 한다면 꽤 복잡했을 텐데, 그런 의미에서 본다면 (닷넷을 포함한) 윈도우 개발자에게 있어 WinRT는 이제 꽤나 쓸만한, 사용해도 좋을 API 셋이 되었습니다.




참고로, 위의 코드를 .NET 7 콘솔 프로젝트에서 수행하려면 프로젝트에서 TargetFramework 값을 다음과 같이 바꿔야 합니다.

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0-windows10.0.19041.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>

"net7.0-windows" 이후에 붙는 버전은 다양할 수 있지만, Windows 10의 경우에는 반드시 최소 19041 이상으로 설정해야 합니다. 만약, 18362 이하로 설정하면 이런 에러가 납니다.

error CS0117: 'AppInfo' does not contain a definition for 'GetFromAppUserModelId'

그나저나, TargetFramework의 버전으로 가용한 값은 어떻게 구할 수 있을까요? 여러 문서를 뒤져봤지만,

Call Windows Runtime APIs in desktop apps
; https://learn.microsoft.com/en-us/windows/apps/desktop/modernize/desktop-to-uwp-enhance

Windows SDK and emulator archive
; https://developer.microsoft.com/en-us/windows/downloads/sdk-archive/

가장 확실한 방법은 그냥 아무 숫자나 넣어보고 오류를 내는 것이었습니다. ^^; 그런 경우 다음과 같이 컴파일 오류가 나면서 허용하는 버전 목록을 보여주기 때문입니다.

// 2023년 11월 9일 기준이며, 향후에는 결과가 달라질 수 있습니다.

1>C:\Program Files\dotnet\sdk\7.0.403\...[생략]...: error NETSDK1140: 5555.0.0.0 is not a valid TargetPlatformVersion for Windows. Valid versions include:
1>C:\Program Files\dotnet\sdk\7.0.403\...[생략]...: error NETSDK1140: 10.0.22621.0
1>C:\Program Files\dotnet\sdk\7.0.403\...[생략]...: error NETSDK1140: 10.0.22000.0
1>C:\Program Files\dotnet\sdk\7.0.403\...[생략]...: error NETSDK1140: 10.0.20348.0
1>C:\Program Files\dotnet\sdk\7.0.403\...[생략]...: error NETSDK1140: 10.0.19041.0
1>C:\Program Files\dotnet\sdk\7.0.403\...[생략]...: error NETSDK1140: 10.0.18362.0
1>C:\Program Files\dotnet\sdk\7.0.403\...[생략]...: error NETSDK1140: 10.0.17763.0
1>C:\Program Files\dotnet\sdk\7.0.403\...[생략]...: error NETSDK1140: 8.0
1>C:\Program Files\dotnet\sdk\7.0.403\...[생략]...: error NETSDK1140: 7.0

출력 결과에서 약간 혼란스러운 것은 Windows 11을 대상으로 하는 경우에도 Major 버전 번호가 10이라는 점입니다. 문서에 보면, 22000 버전 이상은 Windows 11이라고 하고, 그 미만은 Windows 10입니다.

예상했겠지만, 저 버전들은 Windows 10/11의 릴리스/패치 번호에 해당하는데요,

Windows 11 release information
; https://learn.microsoft.com/en-us/windows/release-health/windows11-release-information

Windows 10 release information
; https://learn.microsoft.com/en-us/windows/release-health/release-information

따라서, TargetFramework은 현재 응용 프로그램에서 사용하는 API를 만족시키면서도 가능한 낮은 버전으로 지정하는 것이 좋습니다.




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







[최초 등록일: ]
[최종 수정일: 11/9/2023]

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)
13459정성태11/26/20232338닷넷: 2171. .NET Core 3/5+ 기반의 COM Server를 기존의 regasm처럼 등록하는 방법파일 다운로드1
13458정성태11/26/20232365닷넷: 2170. .NET Core/5+ 기반의 COM Server를 tlb 파일을 생성하는 방법(tlbexp)
13457정성태11/25/20232297VS.NET IDE: 187. Visual Studio - 16.9 버전부터 추가된 "Display inline type hints" 옵션
13456정성태11/25/20232605닷넷: 2169. C# - OpenAI를 사용해 PDF 데이터를 대상으로 OpenAI 챗봇 작성 [1]파일 다운로드1
13455정성태11/25/20232495닷넷: 2168. C# - Azure.AI.OpenAI 패키지로 OpenAI 사용파일 다운로드1
13454정성태11/23/20232843닷넷: 2167. C# - Qdrant Vector DB를 이용한 Embedding 벡터 값 보관/조회 (Azure OpenAI) [1]파일 다운로드1
13453정성태11/23/20232342오류 유형: 879. docker desktop 설치 시 "Invalid JSON string. (Exception from HRESULT: 0x83750007)"
13452정성태11/22/20232446닷넷: 2166. C# - Azure OpenAI API를 이용해 사용자가 제공하는 정보를 대상으로 검색하는 방법파일 다운로드1
13451정성태11/21/20232575닷넷: 2165. C# - Azure OpenAI API를 이용해 ChatGPT처럼 동작하는 콘솔 응용 프로그램 제작파일 다운로드1
13450정성태11/21/20232383닷넷: 2164. C# - Octokit을 이용한 GitHub Issue 검색파일 다운로드1
13449정성태11/21/20232459개발 환경 구성: 688. Azure OpenAI 서비스 신청 방법
13448정성태11/20/20232700닷넷: 2163. .NET 8 - Dynamic PGO를 결합한 성능 향상파일 다운로드1
13447정성태11/16/20232581닷넷: 2162. ASP.NET Core 웹 사이트의 SSL 설정을 코드로 하는 방법
13446정성태11/16/20232534닷넷: 2161. .NET Conf 2023 - Day 1 Blazor 개요 정리
13445정성태11/15/20232852Linux: 62. 리눅스/WSL에서 CA 인증서를 저장하는 방법
13444정성태11/15/20232607닷넷: 2160. C# 12 - Experimental 특성 지원
13443정성태11/14/20232635개발 환경 구성: 687. OpenSSL로 생성한 사용자 인증서를 ASP.NET Core 웹 사이트에 적용하는 방법
13442정성태11/13/20232454개발 환경 구성: 686. 비주얼 스튜디오로 실행한 ASP.NET Core 사이트를 WSL 2 인스턴스에서 https로 접속하는 방법
13441정성태11/12/20232767닷넷: 2159. C# - ASP.NET Core 프로젝트에서 서버 Socket을 직접 생성하는 방법파일 다운로드1
13440정성태11/11/20232437Windows: 253. 소켓 Listen 시 방화벽의 Public/Private 제어 기능이 비활성화된 경우
13439정성태11/10/20232973닷넷: 2158. C# - 소켓 포트를 미리 시스템에 등록/예약해 사용하는 방법(Port Exclusion Ranges)파일 다운로드1
13438정성태11/9/20232584닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
13437정성태11/8/20232757닷넷: 2156. .NET 7 이상의 콘솔 프로그램을 (dockerfile 없이) 로컬 docker에 배포하는 방법
13436정성태11/7/20232985닷넷: 2155. C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능
13435정성태11/6/20232908닷넷: 2154. C# - 네이티브 자원을 포함한 관리 개체(예: 스레드)의 GC 정리
13434정성태11/1/20232687스크립트: 62. 파이썬 - class의 정적 함수를 동적으로 교체
1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...