- Embedding the Windows Media Player Control in a Visual Basic .NET Solution
- Add the Video Window
- Add Two Buttons and Adjust the Form
- Add the Play Code
- Add the Stop Code
- Add Error-handling
- Как работать с Windows media player?
- Решение
- Программирование на VBA в Microsoft Office. Проигрыватель звуковых файлов
- Using the Windows Media Player Control with Visual Basic
- Getting Started
- Object References
- Additional Tips
- Using the Windows Media Player Control with Microsoft Office
Embedding the Windows Media Player Control in a Visual Basic .NET Solution
To use the functionality of Windows Media Player 9 Series or later in a Visual Basic .NET application, first add the component to a form as described in Using the Windows Media Player Control with Microsoft Visual Studio
This section describes how to create an application that plays video and has custom play and stop buttons.
Add the Video Window
Add the Windows Media Player control to a form. Resize the control, and then place it where you want the video window to appear.
Select the Windows Media Player control, then change the uiMode property to «none». This setting hides the UI controls. When the user plays a video, it will appear in the window. For audio-only content, a visualization will appear.
Add Two Buttons and Adjust the Form
Now add two buttons to the form. Select the first button and change the Text property to «Play». Select the second button and change its Text property to «Stop».
Add the Play Code
Double-click the Play button to reveal the Code window. The following code is displayed:
Add this line to the subroutine:
In the preceding code example, «axWindowsMediaPlayer1» is the default name of the Windows Media Player control and «c:\mediafile.wmv» is a placeholder for the name of the media you want to play.
If you have added the digital media content from the Windows Media Player SDK to the library in Windows Media Player, you can use this code instead:
Because the autoStart property is true by default, Windows Media Player will start playing when you set the currentPlaylist or URL property.
Add the Stop Code
Double-click the Stop button to reveal the Code window. The following code is displayed:
Add this line to the subroutine:
The managed-code wrapper for the Windows Media Player control exposes the Controls object as Ctlcontrols to avoid collision with the Controls property inherited from System.Windows.Forms.Control.
Add Error-handling
The Windows Media Player control does not raise an exception when it encounters an error such as an invalid URL. Instead, the control signals an event. Your application should handle error events sent by the Player.
To create an event handler, open the code window for your form class. From the drop-down list at the top of the window, select the Windows Media Player control. A list of events appears in the drop-down list to the right. From that list, select MediaError. The following code is displayed:
The following code could be inserted in the subroutine to provide minimal error-handling capability. Note that information about the error can be retrieved from the _WMPOCXEvents_MediaErrorEvent argument.
Как работать с Windows media player?
Как добавить на форму проигрыватель Windows Media Player
Visual Basic 2010: Как добавить на форму проигрыватель Windows Media Player тот который идет в.
Как в ToolBox добавить «Windows Media Player»
Приветствую, Форумчане! Имеется какая-то возьможность в панель Toolbox добавить ‘Windows Medio.
Управление Windows Media Player из своего приложения
Всем желаю доброго здравия! Возникла потребность в управлении WinMediaPlayer’ом из своего.
Добавить компонент Windows Media Player на форму
У меня Visual Basic 2010 express. Нужно добавить компонент Windows Media Player на форму. Что я.
Решение
Да автор какой-то вздор пишет, по ходу.
Вот http://msdn.microsoft.com/ru-r. s.85).aspx
И на MSDN описан AxWindowsMediaPlayer, у которого таких методов нет.
Добавлено через 3 минуты
Ну есть где-то упоминания о каком-то Interop.WMPLib.dll (именно Interop, а не AxInterop), но раз даже в MSDN описана Ax-версия, то ее и надо использовать.
Вложения
WindowsApplication3.rar (208.0 Кб, 64 просмотров) |
Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.
Как установить Windows Media Player 7 на Windows XP SP3
Как установить WMP 7 на Windows XP SP3 Короче мне нравиться 7 проигрыватель и хочу его.
Как удалить Windows Media Player 11
Ситуация такая: Поставил себе Висту, там плеер был, палёный какой то, во время звучания музыки.
Как можно записать свой голос, сделать аудиофаил на Windows 2000 в Windows Media Player
Привет. Подскажите пожалуйста, как можно записать свой голос, сделать аудиофаил на Win2000.
windows media player как управлять ползунком
Подскажите как контролировать и управлять программно ползунком проигрывания видео файла. .
Программирование на VBA в Microsoft Office. Проигрыватель звуковых файлов
Программирование на VBA в Microsoft Office.
Проигрыватель звуковых файлов
Здесь мы рассмотрим простейший пример применения мультимедиа в приложениях на Visual Basic for Applications — проигрывание WAV-файлов. Толковое озвучивание событий в прикладной программе всегда привлекает внимание пользователей и повышает их интерес к работе с этой программой. Остаётся узнать, как это сделать.
Запустите Word или Excel, откройте документ с примерами прошлой статьи (КГ № __ «…Создаём свои объекты») — объектом dlgFileOpen и формой ownMediaPlayer для выбора WAV-файлов. Вышеозначенный пример таблицы Excel с программами на VBA Вы сможете также найти на http://brestmedia.f2s.com/ в разделе » Скачать «.
Запустите редактор Visual Basic (для начинающих — комбинация Alt+F11). Далее нам понадобится ещё один объект. В окне проекта кликните правой кнопкой мыши и во всплывающем меню выберите пункт «Вставить->» и далее «Модуль класса». В окне свойств назовите класс SoundPlayer.
Теперь в окне исходного текста будем программировать.
Простое проигрывание звука осуществляется функцией WinAPI PlaySound. Её 32-разрядная версия в Win32API именуется PlaySoundA. Она может воспроизводить WAV-файлы, все зарегистрированные системные события и ресурсы из EXE и DLL файлов. Описание её выглядит следующим образом:
Private Declare Function playSound Lib «winmm.dll» _
Alias «PlaySoundA» (ByVal lpszSoundName As String, _
ByVal hMod As Long, ByVal uFlags As Long) As Long
Параметры: lpszSoundName — имя WAV-файла, системного события либо ресурса, которые надо воспроизвести, hMod — источник воспроизведения. Если источник — файл или системное событие, то hMod=0, а если источник — ресурс из EXE или DLL файла, то hMod должен содержать ссылку на загруженный в память ресурс. uFlags — параметры воспроизведения.
Если надо воспроизвести файл, то необходимо устанавливать флаг SND_FILENAME. Если системное событие, то — SND_ALIAS. Если указанное событие или файл не существуют, то функция проигрывает звук, соответствующий системной ошибке.
Дополнительные флаги обозначают: SND_SYNC — синхронное воспроизведение (приложение ожидает завершения проигрывания звука и только потом продолжает работу), SND_ASYNC — асинхронное воспроизведение (приложение не ждёт завершения проигрывания звука, а параллельно продолжает работу), SND_NODEFAULT — в случае ошибки (файл не найден) не проигрывается стандартный звук, SND_NOWAIT — если драйвер звуковой карты занят, не ждать освобождения.
Тут необходимо уточнить, что в приложениях Microsoft Office (как 97, так и 2000) в разных операционных системах (Windows 9x/NT/2000) асинхронное воспроизведение не работает. Почему, мне установить не удалось. Если получится у Вас — сообщите.
Описание остальных свойств и методов класса.
‘Хранит имя последнего проигранного файла
Private PlayFileName As String
‘Хранит имя последнего проигранного события
Private PlaySysMsgAlias As String
‘Остановить текущее проигрывание звука
Public Function PlayStop() As Boolean
Call playSound(«», 0&, SND_NODEFAULT)
‘Виртуальное свойство — при присваивании
‘ему имени WAV-файла проигрывается звук
Property Let PlayFile(ByVal strWAVFileName As String)
Call playSound(strWAVFileName, 0&, _
SND_ASYNC Or SND_NODEFAULT _
Or SND_FILENAME Or SND_NOWAIT)
‘Виртуальное свойство — при чтении возвращает
‘имя последнего проигранного файла
Property Get PlayFile() As String
‘При присваивании названия
‘события проигрывается звук
Property Let PlaySys(ByVal strSysMsgAlias As String)
Call playSound(strSysMsgAlias, 0&, SND_ASYNC Or SND_NODEFAULT Or SND_ALIAS)
‘Возвращает имя последнего проигранного
Property Get PlaySys() As String
Для использования SoundPlayer’а в редакторе Visual Basic откройте для редактирования форму ownMediaPlayer.
Добавьте кнопку проигрывания файла и двойным щелчком мыши по форме перейдите в окно редактирования исходного текста формы.
В разделе описаний добавьте строку:
Dim SNDPlayer As SoundPlayer ‘— объект типа SoundPlayer
‘Метод инициализации формы уже будет выглядеть так:
Private Sub UserForm_Initialize()
‘Создание экземпляра объекта
Set SNDPlayer = New SoundPlayer
Set dlgFiler = New dlgFileOpen
‘Метод обработки события — нажатия
‘кнопки проигрывания звука
Private Sub CommandButton1_Click()
Сохраните набранные программы, перейдите в таблицу Excel и нажмите кнопку запуска формы. Нажмите кнопку выбора файла и укажите WAV-файл. В поле ввода формы появится его полное имя. Теперь нажмите кнопку проигрывания звука и в полной мере насладитесь работой своего творения.
Чтобы достичь более полного контроля над проигрыванием звука, например, воспроизводить звук в интервалах от 2-й секунды до 4,52 секунды, произвольно останавливать проигрывание, делать паузы и продолжать воспроизведение, и т.д., надо пойти другим путём. Необходимо запрограммировать работу приложения с мультимедиа через MCI (Media Control Interface), что мы далее и будем делать.
В следующей статье рассмотрим пример объекта для проигрывания AVI-видеороликов в окне формы через MCI. При этом вывод видео в окне выполняется независимо от основного приложения, т.е. приложение продолжает работу, не ожидая окончания видеоролика.
Пример таблицы Excel с описанными программами на VBA Вы сможете найти на http://brestmedia.f2s.com/ в разделе » Скачать «.
to be continued…
Компьютерная газета. Статья была опубликована в номере 03 за 2002 год в рубрике программирование :: разное
Using the Windows Media Player Control with Visual Basic
This section describes how to use the Windows Media Player 9 Series or later ActiveX control in applications created with Microsoft Visual Basic 6.0.
Getting Started
To add the Windows Media Player control to the toolbox, first select Components from the Project menu. In the Components dialog box, select the check box next to «Windows Media Player». At the bottom of the dialog box, confirm that the selected file is wmp.dll. After closing the dialog box, you can place an instance of the Windows Media Player control on your form in the usual ways.
You can set many control properties using the Properties window. To set some properties you must use the Windows Media Player Properties dialog box, which you open using the «(Custom)» item in the Properties window.
Object References
You use certain Player control properties to get references to particular objects. For example, the cdromCollection property returns a reference to a CdromCollection object. You must assign such a reference to a variable that you declared as the corresponding interface. In the case of the cdromCollection property, for example, you assign its return value to a variable of type IWMPCdromCollection.
Read the Interfaces topic in the Object Model Reference for C++ to identify which objects implement multiple interfaces. In those cases, you must declare an object variable as the highest-numbered interface documented in this SDK to have access to all of the properties and methods of that object. For example, you should assign the value of the Windows Media Player control currentMedia property to a variable declared as IWMPMedia3 to assure that you have access to the getAttributeCountByType and getItemInfoByType methods.
The WindowsMediaPlayer object implements all of the properties and methods of the IWMPCore, IWMPCore2, IWMPCore3, IWMPPlayer, IWMPPlayer2, IWMPPlayer3, and IWMPPlayer4 interfaces. You do not need to declare separate variables for any of these interfaces. You can access all of their members using the name you assigned to your WindowsMediaPlayer instance.
In the Visual Basic Object Browser you will see many interfaces that are intended for private use by the Windows Media Player control, including some that support skin developers. You should use only the objects, properties, methods, and events that are documented in this SDK.
Additional Tips
The reference documentation shows JScript syntax. In JScript, arguments passed to methods are always enclosed in parentheses. In Visual Basic 6.0, arguments passed to methods that do not return a value must not be enclosed in parentheses.
Some properties or methods may not appear in the Auto List code-completion feature in the Visual Basic code editor. You can still use those members by typing their names exactly as they appear in this documentation.
Manage the visual appearance of the control using the uimode property. You can do so in two ways. You can use the Select a mode drop-down list in the Windows Media Player Properties dialog box, or you can type the correct value in the Properties window.
In particular, do not use the visible property to hide the control; instead, assign the value «invisible» to the uimode property.
Using the Windows Media Player Control with Microsoft Office
This section describes how to embed the Windows Media Player 9 Series or later ActiveX control in various documents created using Microsoft Office XP.
In Microsoft Word, Excel, and PowerPointВ®, you embed the control by selecting Object from the Insert menu, then choosing Windows Media Player from the list of available object types. The Windows Media Player control appears in the document at the current location. You can then select Format Control ( Format Object in Excel) from the shortcut menu for the control to adjust the layout, text wrapping style, and other format options. In Word and Excel, you must be in design mode to do this.
Once you have positioned and formatted the control, you can configure it using the Properties dialog box, which is accessible from the Control Toolbox or from the shortcut menu in design mode for Word and Excel. Here you can specify basic Player control properties such as the control name, the URL of a digital media file, and the user interface mode. Setting the uiMode property to «none» hides everything in the control except the video or visualization window, allowing you to add your own buttons and write script code using Visual Basic for Applications (VBA) to handle the button clicks and Player control events.
From the basic Properties dialog box, you can also access the more sophisticated Windows Media Player Control Properties dialog box by double-clicking the «(Custom)» row or by clicking the ellipsis («. «) button after selecting that row. From this dialog box, you can modify all available Player control properties.
You must be careful not to take actions in Player control event handlers that will result in the control being destroyed. For example, if you embed the Windows Media Player control on a slide in a PowerPoint presentation, do not call the PowerPoint Next method from the Player openStateChange event or any other event.
In addition, you should not set the Player.URL property from a Player control event handler.
In FrontPage, add the Windows Media Player control to a webpage by selecting Web Component from the Insert menu. In the Insert Web Component dialog box, select Advanced Controls from the Component type list, then select ActiveX Control from the list of control choices. In the next window of the dialog box, select Windows Media Player. If it is not listed, click Customize and select the Windows Media Player check box in the Control list.
After the Windows Media Player control is embedded, you can position and resize it, and modify its properties by selecting ActiveX Control Properties from the shortcut menu for the control. In the HTML view, the property values that you specify appear in the OBJECT element representing the Windows Media Player control. The object name appears as the ID attribute, and the control properties appear as PARAM tags. The object name gives you access to the Windows Media Player control object model, which you can program using Microsoft JScript. For more information, see Using the Windows Media Player Control in a Web Page.