<font color=purple size=5 face="隶书">无为也,则用天下而有余;有为也,则为天下用而不足。
1、简介
https://docs.microsoft.com/en-us/windows/win32/wmp/about-the-windows-media-player-sdk
Microsoft Windows Media Player 软件开发工具包 (SDK) 提供了用于自定义 Windows Media Player 和 Windows Media Player Mobile 以及使用 Windows Media Player ActiveX 控件和 Windows Media Player Mobile ActiveX 控件的信息和工具。
1.1 WMP控件特点
多种技术都支持嵌入 Windows Media Player 控件,包括:
- Web 浏览器中的 HTML。支持 Microsoft Internet Explorer、Firefox 和 Netscape Navigator 7.1 版浏览器。
- 使用Microsoft Visual C++ ®开发系统创建的程序。
- 使用Microsoft Visual Basic® 6.0创建的程序。
- 使用 .NET Framework 创建的程序,包括用 Visual Basic 和 C# 编程语言编写的程序。
- 微软办公软件。
1.2 WMP开发接口
Microsoft Windows Media Player 控件是使用 Microsoft Component Object Model (COM) 技术的标准 ActiveX 控件。Windows Media Player 功能被提炼为一组遵循标准 COM 准则的编程接口。您可以使用带有 Microsoft JScript 或 Microsoft Visual Basic Scripting Edition (VBScript) 的 Player 控件对象模型,在标准 HTML 网页上对这些接口进行编程。您还可以使用Microsoft JScript在皮肤中对它们进行编程。如果要创建嵌入控件的自定义程序,可以使用多种语言之一,包括 Visual Basic、C++ 和 C#。
脚本语言的播放器对象模型:
ActiveX 使用对象的概念来包含编程功能。Windows Media Player 使用多个对象来划分控件提供的功能。根对象是 Player 对象,其他对象通过特定属性附加到 Player 对象。
下图显示了 Windows Media Player 11 ActiveX 控件对象模型如何用于脚本语言。
在C++中,有时在 .NET 语言中,对象由 COM 接口表示。在 Windows Media Player 对象模型中,COM 接口名称与对象名称相同,但以“IWMP”为前缀。例如,网络对象通过 IWMPNetwork 接口公开。
1.3 WMP开发方式
(1)导入ActiveX控件,拖放ActiveX控件方式
- 工具箱添加ActiveX控件,菜单“工具” -> “选择工具箱项”
- 选择“COM组件”,在你想要选择的控件上面打钩
- 工具箱最下面就多了对应ActiveX控件
- 拖到界面即可使用
(2)动态创建ActiveX控件
- 类向导,快捷键 Ctrl + Shitf + X
- 右边“添加类”,“ActiveX中的MFC控件类”,生成ActiveX控件类
- 在框架或者对话框的初始函数中,调用类的Create函数
(3)COM调用方式
- 类向导,快捷键 Ctrl + Shitf + X
- 右边“添加类”,“类型库中的MFC类”,生成继承COleDispatchDriver的类
- 在框架或者对话框的初始函数中,调用类的CreateDispatch函数
1.4 WMP支持格式
本文列出 Microsoft Windows Media Player 12 支持的多媒体文件类型。 如果在 Windows 中安装新的编解码器,则可能支持其他文件格式。 Windows Media Player 支持的文件类型:
- Windows Media 格式(.asf、.wma、.wmv、.wm)
- Windows Media 元文件(.asx、.wax、.wvx、.wmx、wpl)
- Microsoft 数字视频记录 (.dvr-ms)
- Windows Media 下载程序包 (.wmd)
- 影音交叉存取 (.avi)
- 运动图像专家组(.mpg、.mpeg、.m1v、.mp2、.mp3、.mpa、.mpe、.m3u)
- 音乐器材数字接口(.mid、.midi、.rmi)
- 音频交换文件格式(.aif、.aifc、.aiff)
- Sun Microsystems 和 NeXT(.au、.snd)
- Audio for Windows (.wav)
- CD 音频曲目 (.cda)
- Indeo 视频技术 (.ivf)
- Windows Media Player 外观(.wmz、.wms)
- QuickTime 影片 (.mov)
- MP4 音频文件 (.m4a)
- MP4 视频文件(.mp4、.m4v、.mp4v、.3g2、.3gp2、.3gp、.3gpp)
- Windows 音频文件(.aac、.adt、.adts)
- MPEG-2 TS 视频文件 (.m2ts)
- 免费无损音频编解码器 (.flac)
2、官网代码示例
https://docs.microsoft.com/en-us/previous-versions/windows/desktop/api/wmp/nn-wmp-iwmpplayer4
2.1 Using the Windows Media Player Control in a Console Application
#include "atlbase.h"
#include "atlwin.h"
#include "wmp.h"
int _tmain(int argc, _TCHAR* argv[])
{
CoInitialize(NULL);
HRESULT hr = S_OK;
CComBSTR bstrVersionInfo; // Contains the version string.
CComPtr<IWMPPlayer> spPlayer; // Smart pointer to IWMPPlayer interface.
hr = spPlayer.CoCreateInstance( __uuidof(WindowsMediaPlayer), 0, CLSCTX_INPROC_SERVER );
if(SUCCEEDED(hr))
{
hr = spPlayer->get_versionInfo(&bstrVersionInfo);
}
if(SUCCEEDED(hr))
{
// Show the version in a message box.
COLE2T pStr(bstrVersionInfo);
MessageBox( NULL, (LPCSTR)pStr, _T("Windows Media Player Version"), MB_OK );
}
// Clean up.
spPlayer.Release();
CoUninitialize();
return 0;
}
2.2 Hosting the Windows Media Player Control in a Windows Application
#include "wmp.h"
#include <atlbase.h>
#include <atlcom.h>
#include <atlhost.h>
#include <atlctl.h>
CAxWindow m_wndView; // ActiveX host window class.
CComPtr<IWMPPlayer> m_spWMPPlayer; // Smart pointer to IWMPPlayer interface.
AtlAxWinInit();
CComPtr<IAxWinHostWindow> spHost;
HRESULT hr;
GetClientRect(&rcClient);
m_wndView.Create(m_hWnd, rcClient, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN, WS_EX_CLIENTEDGE);
hr = m_wndView.QueryHost(&spHost);
hr = spHost->CreateControl(CComBSTR(_T("{6BF52A52-394A-11d3-B153-00C04F79FAA6}")), m_wndView, 0);
hr = m_wndView.QueryControl(&m_spWMPPlayer);
These instructions are summarized as follows:
1. add
#include "wmp.h"
#include <atlbase.h>
#include <atlcom.h>
#include <atlhost.h>
#include <atlctl.h>
to the view header file.
2. Declare member variables, as follows to the view class
CAxWindow m_wndView;
CComPtr<IWMPPlayer> m_spWMPPlayer;
3. add AtlAxWinInit();to the App InitInstance().
4. Add local variables:CComPtr<IAxWinHostWindow> spHost;
HRESULT hr;
Note, I also had to add RECT rcClient for a local variable,
but that is not specified in the instructions.
5. Add the following code:
m_wndView.Create(m_hWnd, rcClient, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN, WS_EX_CLIENTEDGE);
hr = m_wndView.QueryHost(&spHost);
hr = spHost->CreateControl(CComBSTR(_T("{6BF52A52-394A-11d3-B153-00C04F79FAA6}")), m_wndView, 0);
hr = m_wndView.QueryControl(&m_spWMPPlayer);
You could put this in OnDraw in the view, or you could
do as I did and create a DisplayMov subroutine that I call
from OnDraw. See code in my original post. Now, set a
breakpoint at the "QueryHost" line, and compile and run.
You will see hr = E_Fail in the auto variables of the
debug window.
To use the Windows Media Player ActiveX control (including the user interface) in a Windows-based program, you must provide an ActiveX control container. ATL provides the CAxWindow class to provide ActiveX host window functionality.
- CWMPHost.h:
// CWMPHost.h : Declaration of the CWMPHost
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
#include "resource.h" // main symbols
#include <oledlg.h>
#include "wmp.h"
#include "CWMPEventDispatch.h"
/////////////////////////////////////////////////////////////////////////////
// CWMPHost
class CWMPHost : public CWindowImpl<CWMPHost, CWindow, CWinTraits<WS_OVERLAPPEDWINDOW | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, WS_EX_APPWINDOW | WS_EX_WINDOWEDGE> >
{
public:
DECLARE_WND_CLASS_EX(NULL, 0, 0)
BEGIN_MSG_MAP(CWMPHost)
MESSAGE_HANDLER(WM_CREATE, OnCreate)
MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
MESSAGE_HANDLER(WM_SIZE, OnSize)
MESSAGE_HANDLER(WM_ERASEBKGND, OnErase)
MESSAGE_HANDLER(WM_CONTEXTMENU, FowardMsgToWMP)
COMMAND_ID_HANDLER(ID_FILE_OPEN, OnFileOpen)
COMMAND_ID_HANDLER(ID_APP_EXIT, OnFileExit)
COMMAND_ID_HANDLER(ID_WMPCORE_CLOSE, OnWMPCoreClose)
COMMAND_ID_HANDLER(ID_WMPCORE_URL, OnWMPCoreURL)
COMMAND_ID_HANDLER(ID_WMPCORE_OPENSTATE, OnWMPCoreOpenState)
COMMAND_ID_HANDLER(ID_WMPCORE_PLAYSTATE, OnWMPCorePlayState)
COMMAND_ID_HANDLER(ID_WMPCORE_VERSIONINFO, OnWMPCoreVersionInfo)
COMMAND_ID_HANDLER(ID_WMPCORE_LAUNCHURL, OnWMPCoreLaunchURL)
COMMAND_ID_HANDLER(ID_WMPCORE_ISONLINE, OnWMPCoreIsOnline)
COMMAND_ID_HANDLER(ID_WMPCORE_STATUS, OnWMPCoreStatus)
COMMAND_ID_HANDLER(ID_WMPCORE_CONTROLS, OnWMPCoreInterface)
COMMAND_ID_HANDLER(ID_WMPCORE_SETTINGS, OnWMPCoreInterface)
COMMAND_ID_HANDLER(ID_WMPCORE_CURRENTMEDIA, OnWMPCoreInterface)
COMMAND_ID_HANDLER(ID_WMPCORE_MEDIACOLLECTION, OnWMPCoreInterface)
COMMAND_ID_HANDLER(ID_WMPCORE_PLAYLISTCOLLECTION, OnWMPCoreInterface)
COMMAND_ID_HANDLER(ID_WMPCORE_NETWORK, OnWMPCoreInterface)
COMMAND_ID_HANDLER(ID_WMPCORE_CURRENTPLAYLIST, OnWMPCoreInterface)
COMMAND_ID_HANDLER(ID_WMPCORE_CDROMCOLLECTION, OnWMPCoreInterface)
COMMAND_ID_HANDLER(ID_WMPCORE_CLOSEDCAPTION, OnWMPCoreInterface)
COMMAND_ID_HANDLER(ID_WMPCORE_ERROR, OnWMPCoreInterface)
COMMAND_ID_HANDLER(ID_WMPCORE2_DVD, OnWMPCoreInterface)
COMMAND_ID_HANDLER(ID_WMPPLAYER_ENABLED, OnWMPPlayerEnabled)
COMMAND_ID_HANDLER(ID_WMPPLAYER_FULLSCREEN, OnWMPPlayerFullScreen)
COMMAND_ID_HANDLER(ID_WMPPLAYER_ENABLECONTEXTMENU, OnWMPPlayerEnableContextMenu)
COMMAND_ID_HANDLER(ID_WMPPLAYER_UIMODE, OnWMPPlayerUIMode)
COMMAND_ID_HANDLER(ID_WMPPLAYER2_STRETCHTOFIT, OnWMPPlayer2StretchToFit)
END_MSG_MAP()
void OnFinalMessage(HWND /*hWnd*/);
LRESULT OnDestroy(UINT /* uMsg */, WPARAM /* wParam */, LPARAM /* lParam */, BOOL& bHandled );
LRESULT OnCreate(UINT /* uMsg */, WPARAM /* wParam */, LPARAM /* lParam */, BOOL& /* bHandled */);
LRESULT OnErase(UINT /* uMsg */, WPARAM /* wParam */, LPARAM /* lParam */, BOOL& /* bHandled */);
LRESULT OnSize(UINT /* uMsg */, WPARAM /* wParam */, LPARAM /* lParam */, BOOL& /* bHandled */);
LRESULT OnFileOpen(WORD /* wNotifyCode */, WORD /* wID */, HWND /* hWndCtl */, BOOL& /* bHandled */);
LRESULT OnFileExit(WORD /* wNotifyCode */, WORD /* wID */, HWND /* hWndCtl */, BOOL& /* bHandled */);
LRESULT OnWMPCoreClose(WORD /* wNotifyCode */, WORD /* wID */, HWND /* hWndCtl */, BOOL& /* bHandled */);
LRESULT OnWMPCoreURL(WORD /* wNotifyCode */, WORD /* wID */, HWND /* hWndCtl */, BOOL& /* bHandled */);
LRESULT OnWMPCoreOpenState(WORD /* wNotifyCode */, WORD /* wID */, HWND /* hWndCtl */, BOOL& /* bHandled */);
LRESULT OnWMPCorePlayState(WORD /* wNotifyCode */, WORD /* wID */, HWND /* hWndCtl */, BOOL& /* bHandled */);
LRESULT OnWMPCoreVersionInfo(WORD /* wNotifyCode */, WORD /* wID */, HWND /* hWndCtl */, BOOL& /* bHandled */);
LRESULT OnWMPCoreLaunchURL(WORD /* wNotifyCode */, WORD /* wID */, HWND /* hWndCtl */, BOOL& /* bHandled */);
LRESULT OnWMPCoreIsOnline(WORD /* wNotifyCode */, WORD /* wID */, HWND /* hWndCtl */, BOOL& /* bHandled */);
LRESULT OnWMPCoreStatus(WORD /* wNotifyCode */, WORD /* wID */, HWND /* hWndCtl */, BOOL& /* bHandled */);
LRESULT OnWMPCoreInterface(WORD /* wNotifyCode */, WORD wID, HWND /* hWndCtl */, BOOL& /* bHandled */);
LRESULT OnWMPPlayerEnabled(WORD /* wNotifyCode */, WORD /* wID */, HWND /* hWndCtl */, BOOL& /* bHandled */);
LRESULT OnWMPPlayerFullScreen(WORD /* wNotifyCode */, WORD /* wID */, HWND /* hWndCtl */, BOOL& /* bHandled */);
LRESULT OnWMPPlayerEnableContextMenu(WORD /* wNotifyCode */, WORD /* wID */, HWND /* hWndCtl */, BOOL& /* bHandled */);
LRESULT OnWMPPlayerUIMode(WORD /* wNotifyCode */, WORD /* wID */, HWND /* hWndCtl */, BOOL& /* bHandled */);
LRESULT OnWMPPlayer2StretchToFit(WORD /* wNotifyCode */, WORD /* wID */, HWND /* hWndCtl */, BOOL& /* bHandled */);
LRESULT FowardMsgToWMP(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
CAxWindow m_wndView;
CComPtr<IWMPPlayer> m_spWMPPlayer;
CComPtr<IConnectionPoint> m_spConnectionPoint;
DWORD m_dwAdviseCookie;
};
- CWMPHost.cpp:
// CWMPHost.cpp : Implementation of the CWMPHost
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
#include "stdafx.h"
#include "CWMPHost.h"
#include "dialogs.h"
/////////////////////////////////////////////////////////////////////////////
// CWMPHost
void CWMPHost::OnFinalMessage(HWND /*hWnd*/)
{
::PostQuitMessage(0);
}
LRESULT CWMPHost::OnCreate(UINT /* uMsg */, WPARAM /* wParam */, LPARAM /* lParam */, BOOL& /* bHandled */)
{
AtlAxWinInit();
CComPtr<IAxWinHostWindow> spHost;
CComPtr<IConnectionPointContainer> spConnectionContainer;
CComWMPEventDispatch *pEventListener = NULL;
CComPtr<IWMPEvents> spEventListener;
HRESULT hr;
RECT rcClient;
m_dwAdviseCookie = 0;
// create window
GetClientRect(&rcClient);
m_wndView.Create(m_hWnd, rcClient, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN, WS_EX_CLIENTEDGE);
if (NULL == m_wndView.m_hWnd)
goto FAILURE;
// load OCX in window
hr = m_wndView.QueryHost(&spHost);
if (FAILMSG(hr))
goto FAILURE;
hr = spHost->CreateControl(CComBSTR(L"{6BF52A52-394A-11d3-B153-00C04F79FAA6}"), m_wndView, 0);
if (FAILMSG(hr))
goto FAILURE;
hr = m_wndView.QueryControl(&m_spWMPPlayer);
if (FAILMSG(hr))
goto FAILURE;
// start listening to events
hr = CComWMPEventDispatch::CreateInstance(&pEventListener);
spEventListener = pEventListener;
if (FAILMSG(hr))
goto FAILURE;
hr = m_spWMPPlayer->QueryInterface(&spConnectionContainer);
if (FAILMSG(hr))
goto FAILURE;
// See if OCX supports the IWMPEvents interface
hr = spConnectionContainer->FindConnectionPoint(__uuidof(IWMPEvents), &m_spConnectionPoint);
if (FAILED(hr))
{
// If not, try the _WMPOCXEvents interface, which will use IDispatch
hr = spConnectionContainer->FindConnectionPoint(__uuidof(_WMPOCXEvents), &m_spConnectionPoint);
if (FAILMSG(hr))
goto FAILURE;
}
hr = m_spConnectionPoint->Advise(spEventListener, &m_dwAdviseCookie);
if (FAILMSG(hr))
goto FAILURE;
return 0;
FAILURE:
::PostQuitMessage(0);
return 0;
}
LRESULT CWMPHost::OnDestroy(UINT /* uMsg */, WPARAM /* wParam */, LPARAM /* lParam */, BOOL& bHandled )
{
// stop listening to events
if (m_spConnectionPoint)
{
if (0 != m_dwAdviseCookie)
m_spConnectionPoint->Unadvise(m_dwAdviseCookie);
m_spConnectionPoint.Release();
}
// close the OCX
if (m_spWMPPlayer)
{
m_spWMPPlayer->close();
m_spWMPPlayer.Release();
}
bHandled = FALSE;
return 0;
}
3、C++测试代码
在基于对话框的MFC应用程序中嵌入了Windows Media Player窗口媒体播放器Activex控件。
-
新建一个基于MFC对话框工程
-
添加ActiveX控件 鼠标右键弹出菜单,选择“插入ActiveX控件”
显示ActvieX控件列表窗口如下:
控件被添加到MFC窗口上。
鼠标右键,添加控件变量。自动生成类文件COCX.h,COCX.cpp。
鼠标右键,选择“类向导”,添加wmp的核心播放类。
从wmp.dll来生成类代码文件。
自动生成类文件CWMPPlayer4.h,CWMPPlayer4.cpp。 将COCX m_player; 改成 CWMPPlayer4 m_player;
然后换一种方式,通过“类型库种的MFC类”,添加其他的wmp封装类。比如controls、settings、playlist等。
这里添加其他5个wmp辅助封装类,如下:
最后,VS代码工程的文件组织结构如下:
-
(1)定义变量
//#include "COCX.h"
#include "CWMPControls.h"
#include "CWMPSettings.h"
#include "CWMPPlaylist.h"
#include "CWMPMedia.h"
#include "CWMPPlayer4.h"
//COCXm_player;
CWMPControls m_control;
CWMPSettings m_set;
CWMPPlaylist m_playlist;
CWMPMedia m_media;
CWMPPlayer4 m_player;
- (2)播放视频文件
char szFileFilter[]=
"Mp3 File(*.mp3)|*.mp3|"
"MPEG File(*.mpeg)|*.mpeg|"
"Media File(*.asf)|*.asf|"
"Video File(*.dat)|*.dat|"
"MPGA File(*.mpga)|*.mpga|"
"Wave File(*.wav)|*.wav|"
"AVI File(*.avi)|*.avi|"
"Movie File(*.mov)|*.mov|"
"Mid File(*.mid;*,rmi)|*.mid;*.rmi|"
"Wma File(*.wma)|*.wma|"
"All File(*.*)|*.*||";
CFileDialog fileDialog( TRUE,NULL,NULL,NULL,szFileFilter,this);
if (fileDialog.DoModal() == IDOK)
{
CString fileName=fileDialog.GetPathName();
m_player.put_URL(fileName);
}
//创建一个播放列表
m_playlist = static_cast<CWMPPlaylist>(m_player.get_currentPlaylist());
m_player.put_fullScreen(tru);
char szFileFilter[]=
"Mp3 File(*.mp3)|*.mp3|"
"MPEG File(*.mpeg)|*.mpeg|"
"Media File(*.asf)|*.asf|"
"Video File(*.dat)|*.dat|"
"MPGA File(*.mpga)|*.mpga|"
"Wave File(*.wav)|*.wav|"
"AVI File(*.avi)|*.avi|"
"Movie File(*.mov)|*.mov|"
"Mid File(*.mid;*,rmi)|*.mid;*.rmi|"
"Wma File(*.wma)|*.wma|"
"All File(*.*)|*.*||";
CFileDialog fileDialog( TRUE,NULL,NULL,NULL,szFileFilter,this);
if (fileDialog.DoModal() == IDOK)
{
CString fileName=fileDialog.GetPathName();
//创建一个媒体
m_media = static_cast<CWMPMedia>(m_player.newMedia(fileName));
//将媒体添加到播放列表
m_playlist.appendItem(m_media);
//将列表添加到当前列表,以便实现自动播放
m_player.put_currentPlaylist(m_playlist);
m_set = (CWMPSettings)m_player.get_settings();
//参数true设置自动播放,false不设置自动播放
m_set.put_autoStart(true);
//将媒体的名字添加到列表控件
m_listCtrl.InsertItem(0, m_media.get_name());
}
m_control = static_cast<CWMPControls>(m_player.get_controls());
m_control.play();
m_control.pause();
m_control.stop();
上面的步骤操作不正确的话,会出现如下的提示框。
4、IE测试代码
<!-- Copyright (c) Microsoft Corporation. All rights reserved. -->
<!-- Windows Media Player SDK Embedded Player Sample -->
<HTML>
<HEAD>
<TITLE>Embedded Player Control Sample</TITLE>
</HEAD>
<BODY onl oad = "Init();">
Embedding Windows Media Player
<H2>Includes custom error handling</H2>
<OBJECT id=Player classid=CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6 height="200" width="200">
<PARAM NAME="autoStart" VALUE="true">
</OBJECT>
<BR><BR>
<INPUT type=button value="Play Audio" name=btnPlayAudio onclick=PlayAudio()>
<INPUT type=button value="Play Video" name=btnPlayVideo onclick=PlayVideo()>
<INPUT type=button value=" Pause " name=btnPause onclick=PauseMe()>
<INPUT type=button value="Stop" name=btnStop onclick=StopMe()>
<INPUT type=button value="Generate Error" name=btnMakeError onclick=MakeError()>
<BR><BR>
<DIV id=divName size=50>Media name: </DIV><BR><BR>
<DIV id=divState size=50>Playstate: </DIV><BR><BR>
<DIV id=divStatus size=50>Status: </DIV><BR><BR>
<SCRIPT language = "JScript">
var g_bPaused = false; // To track pause button state;
// Check for JScript errors.
onerror = ShowError;
// Display JScript errors.
function ShowError (msg,url,linenumber)
{
alert(msg + " at line " + linenumber);
}
// Initialized states.
function Init()
{
Player.uiMode = "none";
btnPause.disabled = true;
btnStop.disabled = true;
// Request Media Libary access rights, if none exists.
if( Player.settings.mediaAccessRights == "none" )
{
// Request access rights.
Player.settings.requestMediaAccessRights( "read" );
}
}
// Play a known audio file from Media Library.
function PlayAudio ()
{
}
// Play a known video file from Media Library.
function PlayVideo ()
{
Player.URL = "d:\\test.mp4";
}
// Try to play a file that doesn't exist.
function MakeError ()
{
StopMe();
Player.URL = "d:\\test.mp4"; // This assumes you don't have a file by this name!
}
// Pause the Player.
function PauseMe ()
{
if( g_bPaused == true )
{
Player.controls.play();
g_bPaused = false;
btnPause.value = " Pause ";
}
else
{
Player.controls.pause();
g_bPaused = true;
btnPause.value = "Resume";
}
}
// Stop the Player.
function StopMe ()
{
Player.controls.stop();
}
</SCRIPT>
<SCRIPT LANGUAGE = "JScript" FOR = Player EVENT = PlayStateChange(NewState)>
// Test for the current state.
// If playing, display the name of the current media.
switch (NewState){
case 1:
divState.innerHTML = "Playstate: Stopped";
// Toggle the button states.
btnPause.disabled = true;
btnPause.value = " Pause ";
btnStop.disabled = true;
break;
case 2:
divState.innerHTML = "Playstate: Paused";
break;
case 3:
divState.innerHTML = "Playstate: Playing";
divName.innerHTML = "Media name: " + Player.currentMedia.name;
// Toggle the button states.
btnPause.disabled = false;
btnStop.disabled = false;
break;
case 6:
divState.innerHTML = "Playstate: Buffering";
break;
case 7:
divState.innerHTML = "Playstate: Waiting";
break;
case 8:
divState.innerHTML = "Playstate: Media Ended";
break;
case 9:
divState.innerHTML = "Playstate: Transitioning";
break;
case 10:
divState.innerHTML = "Playstate: Ready";
break;
// Other cases go here.
default:
divState.innerHTML = "Playstate: Other";
}
</SCRIPT>
<SCRIPT LANGUAGE = "JScript" FOR = Player EVENT = StatusChange()>
divStatus.innerHTML = "Status: " + Player.status;
</SCRIPT>
<SCRIPT LANGUAGE = "JScript" FOR = Player EVENT = Error()>
var strError = "";
// Store the number of errors in the queue.
var max = Player.error.errorCount
// Loop through the list of errors.
for (var i = 0; i < max; i++)
{
// Display the error description for each item.
strError += "Error: " + Player.error.item(i).errorDescription + "\n";
}
alert( strError ); // Display the error warning.
// Clear the error queue to prepare for the next group of errors.
Player.error.clearErrorQueue();
</SCRIPT>
</BODY>
</HTML>
5、C#测试代码
“工具箱”中单击右键,选择“选择项”菜单,打开“选择工具箱项”窗口,选择“COM组件”标签,在列表中找到并勾选“Windows Media Player”组件,单击“确定”按钮。将该组件添加到指定的工具箱选项卡中。
- 添加wmp的com控件引用
- 窗口上添加控件
- 添加逻辑代码
/// <summary>
/// Open new audio from the Library.
/// </summary>
private void btnOpen_Click(object sender, System.EventArgs e)
{
Library libForm = new Library();
libForm.WMPlayer = Player;
libForm.ShowDialog();
if (libForm.DialogResult == DialogResult.OK)
{
try
{
theMedia = libForm.TheMedia;
if(theMedia != null) // Test whether the user chose a media item.
{
lblSongName.Text = theMedia.name;
lblSourceURL.Text = theMedia.sourceURL;
// Set the current media. It will play automatically.
Player.currentMedia = theMedia;
}
}
catch(COMException comExc)
{
int hr = comExc.ErrorCode;
String Message = String.Format("There was an error.\nHRESULT = {1}\n{2}", hr.ToString(), comExc.Message);
MessageBox.Show(Message, "COM Exception");
}
}
}
/// <summary>
/// Play/Pause transport control button handler.
/// </summary>
private void btnPlayPause_Click(object sender, System.EventArgs e)
{
try
{
if(Player.playState == WMPPlayState.wmppsPlaying)
{
Player.Ctlcontrols.pause();
}
else
{
Player.Ctlcontrols.play();
}
}
catch(COMException comExc)
{
int hr = comExc.ErrorCode;
String Message = String.Format("There was an error.\nHRESULT = {1}\n{2}", hr.ToString(), comExc.Message);
MessageBox.Show(Message, "COM Exception");
}
}
/// <summary>
/// Centralize UI state control.
/// </summary>
/// <param name="newState">State of the player</param>
private void SetUIState(WMPPlayState newState)
{
bool canFF, canRew, canPlay, canPause, canSeek, canStop;
double fDuration;
try
{
canFF = Player.Ctlcontrols.get_isAvailable("fastForward");
canRew = Player.Ctlcontrols.get_isAvailable("fastReverse");
canPlay = Player.Ctlcontrols.get_isAvailable("Play");
canPause = Player.Ctlcontrols.get_isAvailable("Pause");
canSeek = Player.Ctlcontrols.get_isAvailable("currentPosition");
canStop = Player.Ctlcontrols.get_isAvailable("Stop");
fDuration = Player.currentMedia.duration;
}
catch(COMException comExc)
{
int hr = comExc.ErrorCode;
String Message = String.Format("There was an error.\nHRESULT = {1}\n{2}", hr.ToString(), comExc.Message);
MessageBox.Show(Message, "COM Exception");
return;
}
}
// 播放rmvb/rm等非官方格式文件要先双击文件再点播放按钮,而不能直接播放的问题,并弹出警告消息框。
// 方法:先设置属性:wmp.settings.enableErrorDialogs = false;事实上这个属性默认就是false。不用设置。
private void wmp_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
//如果已播放完毕就播放下一个文件
if ((WMPLib.WMPPlayState)e.newState == WMPLib.WMPPlayState.wmppsReady)
Player.Ctlcontrols.play();
}
Player.currentMedia.sourceURL; //获取正在播放的媒体文件的路径
Player.currentMedia.name; //获取正在播放的媒体文件的名称
Player.currentMedia.setItemInfo(string); //通过属性名设置媒体信息
Player.currentMedia.name:string; //同 currentMedia.getItemInfo("Title")
Player.currentMedia.duration:double; 媒体总长度
Player.currentMedia.durationString:string; 媒体总长度,字符串格式。如“03:24”
Player.currentMedia.getItemInfo(const string);
获取当前媒体信息:"Title"=媒体标题,"Author"=艺术家,"Copyright"=版权信息,"Description"=媒体内容描述, "Duration"=持续时间(秒),"FileSize"=文件大小,"FileType"=文件类型,"sourceURL"=原始地址
//在视频播放之后,可以通过如下方式读取源视频的宽度和高度,然后设置其还原为原始的大小
int intWidth = Player.currentMedia.imageSourceWidth;
int intHeight = Player.currentMedia.imageSourceHeight;
Player.Width = intWidth + 2;
Player.Height = intHeight + 2;
//播放器基本设置
Player.settings.volume:integer; 音量,0-100
Player.settings.autoStart:Boolean; 是否自动播放
Player.settings.mute:Boolean; 是否静音
Player.settings.playCount:integer; 播放次数
//顺序播放
Player.settings.setMode("shuffle", False)
//随机播放
Player.settings.setMode("shuffle", True)
//循环播放
Player.settings.setMode("loop", True)
//当前播放列表属性
Player.currentPlaylist.count:integer; 当前播放列表所包含媒体数
Player.currentPlaylist.Item[integer]; 获取或设置指定项目媒体信息,其子属性同wmp.currentMedia
Player.AllowChangeDisplaySize //是否允许自由设置播放图象大小
Player.DisplaySize //设置播放图象大小
1-MpDefaultSize //原始大小
2-MpHalfSize //原始大小的一半
3-MpDoubleSize //原始大小的两倍
4-MpFullScreen //全屏
5-MpOneSixteenthScreen //屏幕大小的1/16
6-MpOneFourthScreen //屏幕大小的1/4
7-MpOneHalfScreen //屏幕大小的1/2
Player.ClickToPlay //是否允许单击播放窗口启动Media Player
//播放器基本控制
Player.Ctlcontrols.Play 播放
Player.Ctlcontrols.Stop 停止
Player.Ctlcontrols.Pause 暂停
Player.Ctlcontrols.PlayCount 文件播放次数
Player.Ctlcontrols.AutoRewind 是否循环播放
Player.Ctlcontrols.Balance 声道
Player.Ctlcontrols.Volume 音量
Player.Ctlcontrols.Mute 静音
Player.Ctlcontrols.EnableContextMenu 是否允许在控件上点击鼠标右键时弹出快捷菜单
Player.Ctlcontrols.AnimationAtStart 是否在播放前先播放动画
Player.Ctlcontrols.ShowControls 是否显示控件工具栏
Player.Ctlcontrols.ShowAudioControls 是否显示声音控制按钮
Player.Ctlcontrols.ShowDisplay 是否显示数据文件的相关信息
Player.Ctlcontrols.ShowGotoBar 是否显示Goto栏
Player.Ctlcontrols.ShowPositionControls 是否显示位置调节按钮
Player.Ctlcontrols.ShowStatusBar 是否显示状态栏
Player.Ctlcontrols.ShowTracker 是否显示进度条
Player.Ctlcontrols.FastForward 快进
Player.Ctlcontrols.FastReverse 快退
Player.Ctlcontrols.Rate 快进/快退速率
Player.Ctlcontrols.currentPosition:double; 当前进度
Player.Ctlcontrols.currentPositionString:string; 当前进度,字符串格式。如“00:23”
Player.Ctlcontrols.next; 下一曲
Player.Ctlcontrols.previous; 上一曲
- 测试如下:
<hr/> <center><font color=purple size=7 face=隶书> 最后祝小伙伴们中秋快乐! <br>
标签:控件,Ctlcontrols,MFC,hr,Media,Player,视频文件,ID From: https://blog.51cto.com/u_15800063/5748775