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)
13608정성태4/26/2024417닷넷: 2249. C# - 부모의 필드/프로퍼티에 대해 서로 다른 자식 클래스 간에 Reflection 접근이 동작할까요?파일 다운로드1
13607정성태4/25/2024415닷넷: 2248. C# - 인터페이스 타입의 다중 포인터를 인자로 갖는 C/C++ 함수 연동
13606정성태4/24/2024431닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/2024669닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/2024691오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/2024874닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/2024937닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/2024965닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024975닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024936닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024978닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/2024973닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20241079닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20241069닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241082닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241090닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241226C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241201닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241083Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241158닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241275닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20241361오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241534Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241497Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241457개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...