Windows Media Playerのコントロールです。
Visual Studioから利用するならば、AxWindowsMediaPlayerのコントロールを、ツールボックスからビュー デザイナへ貼り付けるのが簡単です。ただし既定ではこのコントロールはツールボックスに登録されていないため、ツールボックスのコンテキストメニューから[アイテムの選択]を選択し、[COM コンポーネント]にある[Windows Media Player]を選択します。
this.axWindowsMediaPlayer = new AxWMPLib.AxWindowsMediaPlayer(); ((System.ComponentModel.ISupportInitialize)(this.axWindowsMediaPlayer)).BeginInit(); // // axWindowsMediaPlayer // this.axWindowsMediaPlayer.Enabled = true; this.axWindowsMediaPlayer.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axWindowsMediaPlayer.OcxState"))); ((System.ComponentModel.ISupportInitialize)(this.axWindowsMediaPlayer)).EndInit();
末尾のISupportInitialize.EndInit()の呼び出し時に、「ソース オブジェクトは、'IPropertyNotifySink' イベント インターフェイスを公開しません。 (Source object does not expose 'IPropertyNotifySink' event interface.)」として、System.ArgumentException例外が発生することがあります。これは例外設定の[Common Language Runtime Exceptions]にある[System.ArgumentException]を無効にすることで、無視できます。Source object does not expose 'IPropertyNotifySink' event interface error only when debugging
AxWindowsMediaPlayerの導入によりWMPLibが参照に追加されると、「COM 参照 'WMPLib' は ActiveX コントロール 'AxWMPLib' の相互運用アセンブリですが、コンパイラによって /link フラグでリンクされるように設定されています。この COM 参照は参照として処理され、リンクされません。 (COM Reference 'WMPLib' is the interop assembly for ActiveX control 'AxWMPLib' but was marked to be linked by the compiler with the /link flag. This COM reference will be treated as a reference and will not be linked.)」と通知されることがあります。これは、このWMPLibのプロパティで[相互運用型の埋め込み]をfalseとすることで解決できます。
| 型 | プロパティ | 内容 |
|---|---|---|
| string | URL | 再生するメディアのURL
[ファイル名または URL] 無効なURLを指定した場合、enableErrorDialogsがtrueならば「ファイルの再生中に Windows Media Player に問題が発生しました。」としてダイアログで通知される。falseならば何も通知されず、ただ再生できない。 |
| IWMPControls | Ctlcontrols | プレーヤーの制御機能 |
| IWMPMedia | currentMedia | 現在のメディア |
| IWMPSettings | settings | Windows Media Playerの設定 |
| WMPPlayState | playState | プレーヤーの状態 |
| string | status | プレーヤーの状態を表す文字列
"'***' を再生中: *** K ビット/秒"や、"停止"など |
| WMPOpenState | openState | メディア変更時の状態
|
| string | uiMode | コントロールの表示方法
|
| bool | stretchToFit | trueならば、動画がウィンドウより小さいとき、ウィンドウの大きさに広げる
[ウィンドウに合わせる] |
| bool | windowlessVideo | trueならば、クライアント領域に動画を直接描画する。既定のfalseでは、埋め込んだコントロール内に描画する
[ウィンドウなしでビデオを表示する] |
| bool | ctlenabled | trueならば、コントロールによる操作が可能。またフルスクリーンではコントロールが表示される
[コントロールを有効にする] |
| bool | enableContextMenu | trueならば、右クリックされたときにコンテキストメニューが表示される。これがfalseでuiModeが"none"のとき、フルスクリーンではマウスポインタが隠される。
[コンテキスト メニューを有効にする] |
| bool | full-screen | trueならば、フルスクリーンで再生されている
[全画面表示で再生する] |
| string | versionInfo | Windows Media Playerのバージョン。MajorVersion.*.*.BuildNumberの形式の文字列 |
| ︙ |
再生を制御できます。
| 型 | プロパティ | 内容 |
|---|---|---|
| IWMPMedia | currentItem | プレイリストの現在のメディア項目 |
| int | currentMarker | |
| double | currentPosition | 現在の再生位置 [秒単位] |
| string | currentPositionString | 現在の再生位置 [HH:MM:SSの書式の文字列] |
| メソッド | 機能 | |
|---|---|---|
| void | play() | 再生 |
| void | pause() | 一時停止 |
| void | stop() | 停止 |
| void | fastReverse() | 早戻し |
| void | fastForward() | 早送り |
| void | previous() | プレイリストの前の項目へ移動 |
| void | next() | プレイリストの次の項目へ移動 |
| void | playItem(IWMPMedia pIWMPMedia) | 指定の項目を再生 |
| bool | get_isAvailable(string bstrItem) | 指定の機能が有効かどうか調べる |
サポートされないプロパティやメソッドもあり、それはget_isAvailable()で確認できます。たとえばcurrentPositionが有効かどうかは、
player.Ctlcontrols.get_isAvailable("currentPosition")
とすることで確認できます。IWMPControls.isAvailable (VB and C#) (Windows) | MSDN
メディアの長さなどを取得できます。
| 型 | プロパティ | 内容 |
|---|---|---|
| int | attributeCount | getAttributeName()の引数に指定できる、インデックスの上限 |
| double | duration | 現在のメディアの長さ。秒単位 |
| string | durationString | 現在のメディアの長さ。HH:MM:SSの書式での文字列 |
| int | imageSourceHeight | 現在のメディアの高さ。ピクセル単位。映像がない音声ファイルでは0 |
| int | imageSourceWidth | 現在のメディアの幅。ピクセル単位。映像がない音声ファイルでは0 |
| int | markerCount | |
| string | name | |
| string | sourceURL |
| 戻り値の型 | メソッド | 機能 |
|---|---|---|
| string | getAttributeName(int lIndex) | 指定インデックスの属性名を取得 |
| string | getItemInfo(string bstrItemName) | 指定属性の値を取得 |
| void | setItemInfo(string bstrItemName, string bstrVal) | 指定属性の値を設定 |
| bool | isReadOnlyItem(string bstrItemName) | 指定属性の値を設定可能かどうかの判定 |
| string | getItemInfoByAtom(int lAtom) | |
| string | getMarkerName(int MarkerNum) | |
| double | getMarkerTime(int MarkerNum) | |
| bool | get_isIdentical(IWMPMedia pIWMPMedia) | |
| bool | isMemberOf(IWMPPlaylist pPlaylist) |
メディアの読み込みが完了していないと正しい値を取得できないため、MediaChangeイベントの発生を待ってから取得します。
AxWMPLib._WMPOCXEvents_MediaChangeEventHandler handler = null;
handler = delegate (object sender, AxWMPLib._WMPOCXEvents_MediaChangeEvent e)
{
player.MediaChange -= handler;
// 新しいメディア情報の取得
WMPLib.IWMPMedia media = (WMPLib.IWMPMedia)e.item;
};
player.MediaChange += handler;
// メディアの変更
player.URL = newURL;
| 型 | プロパティ | 内容 |
|---|---|---|
| bool | autoStart | [自動的に開始する] |
| int | balance | [バランス] |
| string | baseURL | [ベース URL] |
| string | defaultFrame | [既定のフレーム] |
| bool | enableErrorDialogs | [エラーダイアログを有効にする] |
| bool | invokeURLs | trueならば、URLイベントで既定のブラウザを起動する |
| bool | mute | [ミュート]
(uiModeが"none"のとき、URLの値を更新するとmuteがfalseとなる) |
| int | playCount | [再生カウント] |
| double | rate | [レート] |
| int | volume | [音量] |
| メソッド | 機能 | |
|---|---|---|
| bool | getMode(string bstrMode) | |
| void | setMode(string bstrMode, bool varfMode) |
| 列挙子 | 状態 |
|---|---|
| wmppsUndefined | Windows Media Player is in an undefined state. |
| wmppsStopped | Playback is stopped. |
| wmppsPaused | Playback is paused. |
| wmppsPlaying | Stream is playing. |
| wmppsScanForward | Stream is scanning forward. |
| wmppsScanReverse | Stream is scanning backward. |
| wmppsBuffering | Stream is being buffered. |
| wmppsWaiting | Waiting for streaming data. |
| wmppsMediaEnded | The end of the media item has been reached. |
| wmppsTransitioning | Preparing new media item. |
| wmppsReady | Ready to begin playing. |
| wmppsReconnecting | Trying to reconnect for streaming data. |
| wmppsLast | Last enumerated value. Not a valid state. |
| イベント | 発生タイミング |
|---|---|
| AudioLanguageChange | the current audio language changes. |
| Buffering | the Windows Media Player control begins or ends buffering. |
| CdromBurnError | a generic error happens during a CD burning operation. |
| CdromBurnMediaError | an error happens while burning an individual media item to a CD. |
| CdromBurnStateChange | a CD burning operation changes state. |
| CdromMediaChange | a CD or DVD is inserted into or ejected from a CD or DVD drive. |
| CdromRipMediaError | an error happens while ripping an individual track from a CD. |
| CdromRipStateChange | a CD ripping operation changes state. |
| Click | the user clicks a mouse button. |
| CurrentItemChange | IWMPControls.currentItemプロパティが変更されたとき |
| CurrentMediaItemAvailable | a graphic metadata item in the current media item becomes available. |
| CurrentPlaylistChange | something changes within the current playlist. |
| CurrentPlaylistItemAvailable | the current playlist item becomes available. |
| DomainChange | the DVD domain changes. |
| DoubleClick | the user double-clicks a mouse button. |
| Error | the Windows Media Player control has an error condition. |
| FolderScanStateChange | a folder monitoring operation changes state. |
| KeyDown | a key is pressed. |
| KeyPress | a key is pressed and then released. |
| KeyUp | a key is released. |
| LibraryConnect | a library becomes available. |
| LibraryDisconnect | a library is no longer available. |
| MarkerHit | a marker is reached. |
| MediaChange | メディア項目が変更されたとき |
| MediaCollectionAttributeStringAdded | an attribute value is added to the library. |
| MediaCollectionAttributeStringChanged | an attribute value in the library is changed. |
| MediaCollectionAttributeStringRemoved | an attribute value is removed from the library. |
| MediaCollectionChange | the media collection changes. |
| MediaCollectionMediaAdded | a media item is added to the local library. |
| MediaCollectionMediaRemoved | a media item is removed from the local library. |
| MediaError | the Media object has an error condition. |
| ModeChange | a mode of Windows Media Player is changed. |
| MouseDown | a mouse button is pressed. |
| MouseMove | the mouse pointer is moved. |
| MouseUp | a mouse button is released. |
| OpenPlaylistSwitch | a title on a DVD begins playing. |
| OpenStateChange | the Windows Media Player control changes state. |
| PlaylistChange | a playlist changes. |
| PlaylistCollectionChange | something changes in the playlist collection. |
| PlaylistCollectionPlaylistAdded | a playlist is added to the playlist collection. |
| PlaylistCollectionPlaylistRemoved | a playlist is removed from the playlist collection. |
| PlayStateChange | 再生状態が変更されたとき。再生、停止、バッファリングなど PlayStateChange Event of the AxWindowsMediaPlayer Object (Windows) | MSDN |
| PositionChange | the current position of the media item has been changed. |
| ScriptCommand | a synchronized command or URL is received. |
| StatusChange | statusプロパティの値が変更されたとき |
| StringCollectionChange | a string collection changes. |
IWMPControls.currentItemプロパティが変更されたとき、wmppsReadyとwmppsTransitioningの状態で連続して3回発生します。URLプロパティを変更したときは、MediaChangeイベントの前に発生します。読み込み完了前に発生するため、currentMediaを通してメディアの情報を取得できません。
private void player_CurrentItemChange( object sender, _WMPOCXEvents_CurrentItemChangeEvent e )CurrentItemChange Event of the AxWindowsMediaPlayer Object (Windows) | MSDN
URLプロパティでメディアを変更したときや、一時停止や停止から再生に状態が変化したときに、wmppsPlayingの状態で間を置いて2回発生します。
private void player_MediaChange( object sender, _WMPOCXEvents_MediaChangeEvent e )MediaChange Event of the AxWindowsMediaPlayer Object (Windows) | MSDN
変更後の新しいメディアは、引数のe.itemをキャストすることで取得できます。
private void player_MediaChange(object sender, AxWMPLib._WMPOCXEvents_MediaChangeEvent e)
{
WMPLib.IWMPMedia newMedia = (WMPLib.IWMPMedia)e.item;
}
KeyDownやKeyPressなどのキーイベントは、Windows Media Playerでショートカットキーが割り当てられているキーでは発生しません。
public partial class Form1 : Form, IMessageFilter { public Form1() { InitializeComponent(); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); Application.AddMessageFilter(this); } protected override void OnFormClosing(FormClosingEventArgs e) { base.OnFormClosing(e); Application.RemoveMessageFilter(this); } public bool PreFilterMessage(ref Message m) { const int WM_KEYDOWN = 0x100; if (m.Msg == WM_KEYDOWN) { Keys keyCode = (Keys)m.WParam & Keys.KeyCode; if (keyCode == Keys.Escape) { this.axWindowsMediaPlayer.fullScreen = false; return true; } } return false; } }c# - Axwindows media player dectect keydown in full screen mode - Stack Overflow
Windows Media Playerで設定されているものが適用されます。プログラム上からは、レジストリを書き換えることで変更できるようです。axwindowsmediaplayer change the visualization | MSDN
まずAxWindowsMediaPlayerを使用したアプリケーションを実行するには、対象のコンピューターにWindows Media Playerがインストールされている必要があります。そしてこれを使用したアプリケーションを配布するときには、そのアプリケーションのフォルダに
の2つのファイルを配置します。Distributing Your Application - Using the Windows Media Player Control with Microsoft Visual Studio (Windows) | MSDN
「warning MSB3305: COM 参照 "WMPLib" をパス "C:\WINDOWS\system32\wmp.dll" から処理しています。'IWMPGraphEventHandler.NotifyAcquireCredentials' の引数のうち少なくとも 1 つをランタイム マーシャラーでマーシャリングできません。 したがってこのような引数はポインターとして渡され、アンセーフ コードの使用が必要になります。」
「warning MSB3305: COM 参照 "WMPLib" をパス "C:\WINDOWS\system32\wmp.dll" から処理しています。プロパティ get アクセス操作子 'sessionPlaylistCount' (有効な戻り値の型のない型 'WMPLib.IWMPNowPlayingHelperDispatch' 上) がタイプ ライブラリ インポーターで見つかりました。 インポーターはこのプロパティをメソッドとしてインポートすることを試行します。」