Media Player Classicで再生中の動画・音声のタイトルをC#から取得するアプリを作成しました。
Windows APIのFindWindowとGetWindowTextを使用し、ウィンドウタイトルを解析してトラック名を抽出します。
環境
- Media Player Classic Home Cinema(MPC-HC 64bit 1.7.9)
- .Net Framework 4.6
はじめに
Media Player Classicで再生中のコンテンツ情報を外部アプリケーションから取得する必要があったため、C#を使ってMPCから現在再生中のタイトルを取得するアプリケーションを作成しました。
ソースコード
本アプリのソースコードです。コンソールアプリケーションとして作成しました。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
internal class Program
{
static void Main(string[] args)
{
string track = MPCHelper.GetCurrentTrackName();
if (track != null)
{
Console.WriteLine("タイトル:" + track);
}
else
{
Console.WriteLine("取得できませんでした");
}
}
}
public static class MPCHelper
{
[DllImport("user32.dll")]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
public static string GetCurrentTrackName()
{
IntPtr handle = FindWindow("MediaPlayerClassicW", null);
if (handle == IntPtr.Zero)
{
return null;
}
StringBuilder sb = new StringBuilder(512);
GetWindowText(handle, sb, sb.Capacity);
string title = sb.ToString();
if (string.IsNullOrWhiteSpace(title))
{
return null;
}
int index = title.LastIndexOf(" - ");
if (index > 0)
{
return title.Substring(0, index).Trim();
}
return title;
}
}
}ソースコードについて
Windows APIのFindWindowとGetWindowTextを組み合わせることで実現しています。
処理の流れとしては以下のようになります。
1.FindWindowでMPC(ウィンドウクラス名:MediaPlayerClassicW)のウィンドウハンドルを取得
2.GetWindowTextでウィンドウタイトルを取得
3.ウィンドウタイトルは「タイトル – ファイル名」の形式なので、最後の「 – 」で分割してタイトル部分を抽出
使用方法
コマンドプロンプトからコンソールアプリケーションとして実行すると、MPCが起動していれば現在再生中のタイトルが表示されます。
C:\Workspace>MPCtitle.exe タイトル:サンプル.flac
MPCが起動していない場合は「取得できませんでした」と表示されます。
C:\Workspace>MPCtitle.exe 取得できませんでした
何も再生されていない場合は、アプリ名が表示されます。
C:\Workspace>MPCtitle.exe タイトル:Media Player Classic Home Cinema
注意点
本アプリはMPCのウィンドウタイトルを取得しているだけで、再生状態などを取得しているわけではないので、コンテンツが停止している状態で実行してもタイトルが取得される場合があります。
再生中のみ取得したいなど、MPCの状態によって細かく制御したい場合は別途方法を検討する必要があります。
まとめ
シンプルなコード量で実装でき、他のアプリケーションとの連携にも応用できます。ぜひ参考にしてみてください。



コメント