Воспроизведение видео
Для воспроизведения видео в Visual Basic чаще всего используется
элемент управления Windows Media Player, входящий в
комплект ActiveX-компонентов Windows. Это позволяет встроить мощный
медиаплеер прямо в форму VB-приложения с минимальными усилиями.
Подключение
компонента Windows Media Player
- Откройте ваш проект в Visual Studio.
- Перейдите в меню Tools → Choose Toolbox
Items…. - Перейдите на вкладку COM Components.
- Установите галочку на Windows Media Player
(wmp.dll
) и нажмите OK. - Перетащите компонент
AxWindowsMediaPlayer
на форму из
панели Toolbox.
На форме появится элемент плеера — по умолчанию он будет называться
AxWindowsMediaPlayer1
.
Основные свойства и методы
Свойство URL
Для задания файла к воспроизведению используется свойство
URL
. Пример:
AxWindowsMediaPlayer1.URL = "C:\Videos\example.mp4"
После установки пути к файлу воспроизведение начинается
автоматически.
Метод Ctlcontrols.play
Если вы хотите вручную запускать воспроизведение:
AxWindowsMediaPlayer1.Ctlcontrols.play()
Аналогично доступны:
pause()
— приостановить воспроизведение;stop()
— остановить и вернуть воспроизведение к
началу.
Пример:
AxWindowsMediaPlayer1.Ctlcontrols.pause()
Работа с пользовательским
интерфейсом
Вы можете скрыть стандартные элементы управления Windows Media Player
и создать собственные кнопки:
AxWindowsMediaPlayer1.uiMode = "none"
Значения uiMode
:
"full"
— интерфейс со всеми стандартными кнопками;"mini"
— только базовые элементы управления;"none"
— скрыть интерфейс (только видео);"invisible"
— плеер не отображается, но воспроизводит
звук.
Создание пользовательских кнопок:
Private Sub btnPlay_Click(sender As Object, e As EventArgs) Handles btnPlay.Click
AxWindowsMediaPlayer1.Ctlcontrols.play()
End Sub
Private Sub btnPause_Click(sender As Object, e As EventArgs) Handles btnPause.Click
AxWindowsMediaPlayer1.Ctlcontrols.pause()
End Sub
Private Sub btnStop_Click(sender As Object, e As EventArgs) Handles btnStop.Click
AxWindowsMediaPlayer1.Ctlcontrols.stop()
End Sub
Обработка событий
воспроизведения
AxWindowsMediaPlayer
предоставляет множество событий.
Примеры:
Событие
PlayStateChange
Позволяет реагировать на изменения состояния плеера:
Private Sub AxWindowsMediaPlayer1_PlayStateChange(sender As Object, e As AxWMPLib._WMPOCXEvents_PlayStateChangeEvent) Handles AxWindowsMediaPlayer1.PlayStateChange
Select Case e.newState
Case 1
lblStatus.Text = "Остановлено"
Case 3
lblStatus.Text = "Воспроизведение"
Case 2
lblStatus.Text = "Пауза"
End Select
End Sub
Событие MediaError
Если при загрузке видео возникает ошибка:
Private Sub AxWindowsMediaPlayer1_MediaError(sender As Object, e As AxWMPLib._WMPOCXEvents_MediaErrorEvent) Handles AxWindowsMediaPlayer1.MediaError
MessageBox.Show("Ошибка при загрузке файла.")
End Sub
Воспроизведение из интернета
Для воспроизведения видео с URL:
AxWindowsMediaPlayer1.URL = "https://example.com/video.mp4"
Важно: видеофайл должен быть доступен для прямой передачи по HTTP или
HTTPS без необходимости авторизации или редиректов.
Поддерживаемые форматы
Windows Media Player поддерживает следующие форматы (в зависимости от
установленных кодеков и версии Windows):
- Видео:
.mp4
,.avi
,.wmv
,
.mov
- Аудио:
.mp3
,.wav
,.wma
Формат .mp4
с кодеком H.264 обычно работает корректно в
современных системах.
Полноэкранный режим
Чтобы включить полноэкранный режим:
AxWindowsMediaPlayer1.fullScreen = True
Можно вызвать это, например, по двойному клику на плеере:
Private Sub AxWindowsMediaPlayer1_DoubleClickEvent(sender As Object, e As EventArgs) Handles AxWindowsMediaPlayer1.DoubleClickEvent
AxWindowsMediaPlayer1.fullScreen = True
End Sub
Получение текущей
позиции и длительности
Для отображения времени воспроизведения:
Dim currentPos As Double = AxWindowsMediaPlayer1.Ctlcontrols.currentPosition
Dim duration As Double = AxWindowsMediaPlayer1.currentMedia.duration
lblTime.Text = $"{FormatTime(currentPos)} / {FormatTime(duration)}"
Форматирование времени:
Private Function FormatTime(seconds As Double) As String
Dim ts As TimeSpan = TimeSpan.FromSeconds(seconds)
Return ts.ToString("mm\:ss")
End Function
Перемотка и позиционирование
Перемотка на определённую позицию:
AxWindowsMediaPlayer1.Ctlcontrols.currentPosition = 60 ' Перейти на 1:00
Также можно реализовать трекбар для перемотки.
Встраивание субтитров
и управление звуком
Громкость:
AxWindowsMediaPlayer1.settings.volume = 50 ' От 0 до 100
Включение / отключение звука:
AxWindowsMediaPlayer1.settings.mute = True
Субтитры
Если в файле есть встроенные субтитры, они могут отображаться
автоматически. Однако AxWindowsMediaPlayer не предоставляет гибкого API
для управления внешними файлами .srt
.
Для профессионального управления субтитрами лучше использовать
сторонние библиотеки (например, VLC ActiveX), но в рамках Visual Basic и
WMP это ограничено.
Ограничения и альтернативы
Хотя Windows Media Player достаточно удобен, он имеет некоторые
ограничения:
- Отсутствие поддержки современных форматов без дополнительных
кодеков; - Проблемы с внешними субтитрами;
- Не всегда предсказуемое поведение в старых версиях Windows.
Альтернативы:
- VLC ActiveX Plugin — мощная замена с поддержкой
всех форматов и субтитров. - DirectShow — низкоуровневый доступ к медиа-ресурсам
через COM-интерфейсы (требует больше кода). - FFmpeg — сторонняя библиотека для продвинутых
задач, но требует обёртки.
Introduction
In Visual Basic NET, the ability to loop a song with Windows Media Player is a common requirement for many applications. This feature allows you to continuously play a song or a playlist without any interruptions. In this article, we will explore how to achieve this functionality using the Visual Basic NET programming language.
Windows Media Player Control
To loop a song with Windows Media Player in Visual Basic NET, we need to utilize the Windows Media Player control. This control provides a set of properties and methods that allow us to interact with the media player and control its playback.
Example
Let’s start by adding the Windows Media Player control to our form. To do this, follow these steps:
- Open Visual Studio and create a new Windows Forms Application project.
- Drag and drop the Windows Media Player control from the Toolbox onto your form.
Once you have added the control, you can use the following code to loop a song:
' Set the URL of the media file
AxWindowsMediaPlayer1.URL = "C:PathToYourSong.mp3"
' Enable the loop property
AxWindowsMediaPlayer1.settings.setMode("loop", True)
' Play the song
AxWindowsMediaPlayer1.Ctlcontrols.play()
In the above example, we first set the URL property of the Windows Media Player control to the path of the song file we want to play. Then, we enable the loop property by calling the setMode method and passing “loop” as the mode and True as the value. Finally, we call the play method to start playing the song.
Additional Options
There are additional options available to customize the looping behavior. For example, you can specify the number of times the song should loop before stopping. To do this, you can modify the setMode method call as follows:
' Set the loop count to 3
AxWindowsMediaPlayer1.settings.setMode("loop", 3)
In the above code, the song will loop three times before stopping. You can adjust the loop count as per your requirements.
Conclusion
Looping a song with Windows Media Player in Visual Basic NET is a straightforward process. By utilizing the Windows Media Player control and its properties, you can easily achieve continuous playback of songs or playlists. Remember to set the URL property, enable the loop property, and call the play method to start playing the song. Additionally, you can customize the looping behavior by specifying the loop count. With these techniques, you can create applications that provide seamless and uninterrupted music playback.
CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.
Introduction
One of the first questions I get asked by my students is how to play movies or music through Visual Basic. I know of four different ways, depending on which Operating System you are on. Today I will cover the first option: Windows Media Player. Today we will learn how to embed Windows Media Player into our program and play any form of media through it.
Design
Start a new Visual Basic Windows Application and add the following controls to it:
- OpenFileDialog
- Menu with the following Subitems
- File
- Browse
- Resize
- Exit
- Player
- Volume Up
- Volume Down
- Mute
- Play
- Stop
- Mode
- Invisible
- None
- Mini
- Full
- File
- Windows Media Player Control. Follow these steps:
- Right click your Toolbox
- Select Choose Items…
- Select the COM Tab
- Scroll Down to Windows Media Player
- If you don’t find it on the list, Browse to the Wmp.dll file inside C:\Windows\System32
You can name all your objects as you wish; keep in mind though that mine would be different, so please look carefully before copying and pasting my code directly. Very important: Set your Form’s KeyPreview property to True. This will allow the form to intercept all keyboard input, as you will see.
Your completed design should look more or less like Figure 1.
Figure 1 – Our Design
Code
Add the KeyDown event to your Form, and enter the following:
Private Sub frmMedia_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown 'Determine Key Pressed - Form KeyPreview Is Set To True Select e.KeyCode Case Keys.Add ' Plus Key wmpPlayer.settings.volume = wmpPlayer.settings.volume + 2 ' Increase Volume Case Keys.Subtract 'Minus Key If wmpPlayer.settings.volume > 0 Then 'If Greater Than 0 wmpPlayer.settings.volume = wmpPlayer.settings.volume - 2 'Decrease Volume wmpPlayer.settings.mute = False 'Enable Mute Button Else '0 Or Less wmpPlayer.settings.mute = True 'Muted Is True, Disable Mute Button End If Case Keys.Divide '/ wmpPlayer.settings.mute = Not wmpPlayer.settings.mute 'Mute End Select End Sub
As mentioned earlier, because the KeyPreview Property is set to true for the Form, the Form intercepts all keyboard input. This is the most apt place to handle any of our ‘hotkeys’ for our program.
When Plus ( + ) is pressed, it increases the volume in increments of 2.
When Minus ( – ) is pressed, it makes sure that the volume is greater than 0, before enabling the Mute button.
When Divide ( / ) is pressed, it mutes the volume.
Now let us proceed with the File Menu’s submenus.
Add the following three events:
Private Sub BrowseToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles BrowseToolStripMenuItem.Click 'Set Filter For OFD ofdOpen.Filter = "AVI Files|*.avi|MPG Files|*.mpg|MP4 Files|*.mp4|WMV Files|*.wmv|All Files|*.*" If ofdOpen.ShowDialog = Windows.Forms.DialogResult.OK Then 'If Valid File Selected wmpPlayer.URL = ofdOpen.FileName 'Play PlayPauseToolStripMenuItem.Text = "Pause" 'Change 'Play' To 'Pause' On Menu End If End Sub Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click Application.Exit() 'Exit End Sub Private Sub ResizeToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ResizeToolStripMenuItem.Click wmpPlayer.Size() = Me.ClientRectangle.Size 'Make Same Size As Form End Sub
The Browse menu item allows us to select AVI, MPG, MP4 as well as WMV options. Obviously we can add MP3 here as well, specifically for audio. Just a note: MP 4 files may not work if Windows Media Player doesn’t have the correct codec to play them.
Exit, exits our application.
Resize, resizes the Media Player according to the form’s size in the event of the form being resized.
Now, let us add the Player menu’s sub items:
Private Sub VolumeUpToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles VolumeUpToolStripMenuItem.Click wmpPlayer.settings.volume = wmpPlayer.settings.volume + 2 'Increase Volume End Sub Private Sub VolumeDownToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles VolumeDownToolStripMenuItem.Click 'Same As When - Pressed If wmpPlayer.settings.volume > 0 Then wmpPlayer.settings.volume = wmpPlayer.settings.volume - 2 wmpPlayer.settings.mute = False Else wmpPlayer.settings.mute = True End If End Sub Private Sub MuteToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles MuteToolStripMenuItem.Click wmpPlayer.settings.mute = Not wmpPlayer.settings.mute 'Swith Between Mute & UnMuted End Sub Private Sub PlayPauseToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles PlayPauseToolStripMenuItem.Click If PlayPauseToolStripMenuItem.Text = "Play" Then 'Switch Between Playing & Pausing wmpPlayer.Ctlcontrols.play() PlayPauseToolStripMenuItem.Text = "Pause" Else wmpPlayer.Ctlcontrols.pause() PlayPauseToolStripMenuItem.Text = "Play" End If End Sub Private Sub StopToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles StopToolStripMenuItem.Click wmpPlayer.Ctlcontrols.stop() 'Stop End Sub Private Sub InvisibleToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles InvisibleToolStripMenuItem.Click ''Windows Media Player is embedded without any visible user interface wmpPlayer.uiMode = "invisible" End Sub Private Sub NoneToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NoneToolStripMenuItem.Click 'Windows Media Player is embedded without controls, 'and with only the video or visualization window displayed wmpPlayer.uiMode = "none" End Sub Private Sub MiniToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles MiniToolStripMenuItem.Click 'Windows Media Player is embedded with the status window, 'play/pause, stop, mute, and volume controls shown in 'addition to the video or visualization window wmpPlayer.uiMode = "mini" End Sub
The first few items concerning the Volume, are identical to our KeyDown event. Yes, I could have made one central sub procedure for all, but this is afterall a basic introduction.
The Play menu item will switch between ‘Play’ and ‘Pause’ depending on the state of the player. If it is playing an item, it shows ‘Pause’. If it was paused, it should show ‘Play’.
Stop stops all media.
The Mode setting determines how the Windows Media Player object looks. This means that depending on what setting has been chosen, the buttons, volume controls, etc. might be displayed or not. You can feel free to experiment with that setting. For more information regarding the uimode property, have a look here.
Conclusion
There you have it, not too complicated hey? Nope. I am including the source files with this article. Check out Part 2 – Playing Youtube and Flash videos from Visual Basic.NET. That is very exciting, but don’t let me get ahead of myself here. Until then, Cheers!
About the Author:
Hannes du Preez is a Microsoft MVP for Visual Basic for the fifth year in a row. He is a trainer at a South African-based company providing IT training in the Vaal Triangle. You could reach him at hannes [at] ncc-cla [dot] com
Submitted by joken on Monday, September 2, 2013 — 13:50.
In this tutorial we’re going to focus on using Windows Media Player in Visual Basic .Net where user is able to play music, videos and viewing of different formats of pictures. Basically the Windows Media Player does not exist in the components portion of the toolbox. So to add the Windows Media Player we need to add it in the toolbox. The first step would be, go to the toolbox and Right click then select Choose Items and the Customize Toolbox dialog box will open. Then Select Windows Media Player on the COM Components. Then click ok. After this step the Windows Media Player control will appear on the current tab. After this process we can add now Windows Media Player to our Form and the default name of this control is “AxWindowsMediaPlayer1”. And these can be changed according to what we wanted for example “myPlayer” so that it could be more easily to read and remember.
The next process is that we’re going to add other controls to our form such as Listbox, FolderBrowserDialog, MenuStrip and StatusStrip.
Plan the objects and Properties
Object Property Settings Form1 Name mainFrm Text Personal Media Player StartPosition CenterScreen ControlBox False AxWindowsMediaPlayer1 Name myPlayer Listbox Name List MenuStrip1 Name MenuStrip1 StatusStrip1 Name StatusStrip1 FolderBrowserDialog1 Name FolderBrowserDialog1
On the MenuStrip1 we need to add two main menus such Libraries and View. The Libraries have also submenus like Music, Videos, Images and Exit. And for the View submenu is only Playlist Editor. This should look like as shown below.
And the final design looks like as shown below.
After designing our user interface let’s proceed in adding functionalities to our program. First step double click the main form or we have name it into “mainFrm” to shift our view Designer into view Code. Then on the mainFrm_Load add this code.
-
list.Items.Clear() ‘ clear all currect content of the list
-
list.Hide() ‘ it will hide the on the main form
-
myPlayer.Width = 787 ‘ it will resize the width of myPlayer into 787
and on below of our Public Class mainFrm add this declaration of variable that will hold full path of our folder. And it will like this.
-
Public Class mainFrm
-
Dim folderpath As String
After adding this code we’re going create a sub procedure that we will be using it for our program later.
-
Public Sub jokenresult()
-
If list.Items.Count > 0 Then
-
list.Show()
-
myPlayer.Width = 577
-
statresult.Text = list.Items.Count & » Items»
-
Else
-
list.Hide()
-
myPlayer.Width = 787
-
End If
-
End Sub
Next we will add functionality to the one sub menu items under libraries the Music. To do this just simply double click the Music sub menu. Then you will be redirected to source code view and add this code so it should now look like as shown below.
-
Private Sub MusicToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MusicToolStripMenuItem.Click
-
Try
-
‘it will open the folder dialog where you can select where is the specific folder of your music
-
FolderBrowserDialog1.ShowDialog()
-
If DialogResult.OK Then
-
‘if true that if you click ok on the folder dialog box then
-
‘it will get the selected path of your folder and store it into di variable
-
Dim di As New IO.DirectoryInfo(FolderBrowserDialog1.SelectedPath)
-
‘in this line of code it will get all the specific file that has the .mp3 extension and store it into diar1 variable
-
Dim diar1 As IO.FileInfo() = di.GetFiles(«*.mp3»)
-
Dim dra As IO.FileInfo
-
‘and in this line it will gather all information with regardsto fullpath and names of all files and store it to the folderpath variable
-
folderpath = di.FullName.ToString
-
list.Items.Clear()
-
‘ list the names of all files in the specified directory
-
For Each dra In diar1
-
Dim a As Integer = 0
-
‘ a = a + 1
-
list.Items.Add(dra)
-
Next
-
‘it will call the sub procedure jokenresult() to perform some actions
-
jokenresult()
-
End If
-
Catch ex As Exception
-
‘if errors occur then the program will catch it and send it back to the user.
-
MsgBox(ex.Message, MsgBoxStyle.Information)
-
End Try
-
End Sub
And this is the sample running program playing a selected music.
And this is the sample running program playing a selected Movie.
And finally this is all of the source code.
-
‘Description: Personal Media Player that enables user to play Music,Video and pictures etc…
-
‘Author: Joken Villanueva
-
‘Date Created:March 23, 2011
-
‘Modified By:
-
Public Class mainFrm
-
Dim folderpath As String
-
Private Sub MusicToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MusicToolStripMenuItem.Click
-
Try
-
‘it will open the folder dialog where you can select where is the specific folder of your music
-
FolderBrowserDialog1.ShowDialog()
-
If DialogResult.OK Then
-
‘if true that if you click ok on the folder dialog box then
-
‘it will get the selected path of your folder and store it into di variable
-
Dim di As New IO.DirectoryInfo(FolderBrowserDialog1.SelectedPath)
-
‘in this line of code it will get all the specific file that has the .mp3 extension and store it into diar1 variable
-
Dim diar1 As IO.FileInfo() = di.GetFiles(«*.mp3»)
-
Dim dra As IO.FileInfo
-
‘and in this line it will gather all information with regardsto fullpath and names of all files and store it to the folderpath variable
-
folderpath = di.FullName.ToString
-
list.Items.Clear()
-
‘ list the names of all files in the specified directory
-
For Each dra In diar1
-
Dim a As Integer = 0
-
‘ a = a + 1
-
list.Items.Add(dra)
-
Next
-
‘it will call the sub procedure jokenresult() to perform some actions
-
jokenresult()
-
End If
-
Catch ex As Exception
-
‘if errors occur then the program will catch it and send it back to the user.
-
MsgBox(ex.Message, MsgBoxStyle.Information)
-
End Try
-
End Sub
-
Public Sub jokenresult()
-
If list.Items.Count > 0 Then
-
list.Show()
-
myPlayer.Width = 577
-
statresult.Text = list.Items.Count & » Items»
-
Else
-
list.Hide()
-
myPlayer.Width = 787
-
End If
-
End Sub
-
Private Sub list_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles list.SelectedIndexChanged
-
‘the myPlayer will play or display something from the list based on the user selected item
-
myPlayer.URL = folderpath & «\» & list.SelectedItem.ToString
-
End Sub
-
Private Sub VideosToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles VideosToolStripMenuItem.Click
-
Try
-
FolderBrowserDialog1.ShowDialog()
-
If DialogResult.OK Then
-
Dim di As New IO.DirectoryInfo(FolderBrowserDialog1.SelectedPath)
-
Dim diar1 As IO.FileInfo() = di.GetFiles(«*.*»)
-
Dim dra As IO.FileInfo
-
folderpath = di.FullName.ToString
-
list.Items.Clear()
-
For Each dra In diar1
-
list.Items.Add(dra)
-
Next
-
jokenresult()
-
End If
-
Catch ex As Exception
-
MsgBox(ex.Message, MsgBoxStyle.Information)
-
End Try
-
End Sub
-
Private Sub ImagesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ImagesToolStripMenuItem.Click
-
Try
-
FolderBrowserDialog1.ShowDialog()
-
If DialogResult.OK Then
-
Dim di As New IO.DirectoryInfo(FolderBrowserDialog1.SelectedPath)
-
Dim diar1 As IO.FileInfo() = di.GetFiles(«*.jpg»)
-
Dim dra As IO.FileInfo
-
folderpath = di.FullName.ToString
-
list.Items.Clear()
-
For Each dra In diar1
-
list.Items.Add(dra)
-
Next
-
jokenresult()
-
End If
-
Catch ex As Exception
-
MsgBox(ex.Message, MsgBoxStyle.Information)
-
End Try
-
End Sub
-
Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
-
End Sub
-
Private Sub PlaylistEditorToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PlaylistEditorToolStripMenuItem.Click
-
‘in this line if the playlist editor is click then the list will sho on the form.
-
If PlaylistEditorToolStripMenuItem.Checked = True Then
-
list.Show()
-
myPlayer.Width = 577
-
Else
-
list.Hide()
-
myPlayer.Width = 787
-
End If
-
End Sub
-
Private Sub mainFrm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
-
list.Items.Clear() ‘ clear all currect content of the list
-
list.Hide() ‘ it will hide the on the main form
-
myPlayer.Width = 787 ‘ it will resize the width of myPlayer into 787
-
End Sub
-
End Class
Comments
Add new comment
- 1959 views
In this tutorial, i will be teaching you How to Make Media Player Using Visual Basic.net Programming Language that is capable of playing sounds,Videos and viewing of images in different format.
So let’s get started. But since Media Player does not exist in the component portion of toolbox, we need to add the Windows Media Player to the toolbox. To do this, just follow the given steps.
What is Visual Basic’s purpose?
The third-generation programming language was created to aid developers in the creation of Windows applications. It has a programming environment that allows programmers to write code in.exe or executable files.
They can also utilize it to create in-house front-end solutions for interacting with huge databases. Because the language allows for continuing changes, you can keep coding and revising your work as needed.
However, there are some limits to the Microsoft Visual Basic download. If you want to make applications that take a long time to process, this software isn’t for you.
That implies you won’t be able to use VB to create games or large apps because the system’s graphic interface requires a lot of memory and space.
Furthermore, the language is limited to Microsoft and does not support other operating systems.
What are the most important characteristics of Visual Basic?
Microsoft Visual Basic for Applications Download, unlike other programming languages, allows for speedier app creation. It has string processing capabilities and is compatible with C++, MFC, and F#.
Multi-targeting and the Windows Presentation Framework are also supported by the system, allowing developers to create a variety of Windows apps, desktop tools, metro-style programs, and hardware drivers.
- Go to the toolbox and Right click
- Then select Choose Items and the Customize Toolbox dialog box will open.
- And select Windows Media Player on the COM Components.
- Then click “OK“
- And finally, Windows Media Player control will appear on the current tab.
After this process we can add now Windows Media Player to our Form and the default name of this control is “AxWindowsMediaPlayer1“. Then you are free to change the name of this object based on what you desire for instance you to name it as “WMPlayer” so that it could be more easily to read and remember.
The next process is that we’re going to add other controls to our form such as Listbox, FolderBrowserDialog, MenuStrip and StatusStrip.
Plan the objects and Properties
Object |
Property |
Settings |
Form1 | Name | mainFrm |
Text | Personal Media Player | |
StartPosition | CenterScreen | |
ControlBox | False | |
AxWindowsMediaPlayer1 | Name | myPlayer |
Listbox | Name | List |
MenuStrip1 | Name | MenuStrip1 |
StatusStrip1 | Name | StatusStrip1 |
FolderBrowserDialog1 | Name | FolderBrowserDialog1 |
On the MenuStrip1 we need to add two main menus such Libraries and View. The Libraries has also sub menus like Music, Videos, Images and Exit. And for the View sub menu is only Playlist Editor. This should look like as shown below.
And the final design is look like as shown below.
After designing our user interface let’s proceed in adding functionalities to our program. First step double click the main form or we have name it into “mainFrm” to shift our view Designer into view Code. Then on the mainFrm_Load add this code.
[vb]
list.Items.Clear() ' clear all currect content of the list
list.Hide() ' it will hide the on the main form
myPlayer.Width = 787 ' it will resize the width of myPlayer into 787
[/vb]
and on below of our Public Class mainFrm add this declaration of variable that will hold later path of our folder. And it will like this.
[vb]
Public Class mainFrm
Dim folderpath As String
[/vb]
After adding this code we’re going create a sub procedure that we will be using it for our program later.
[vb]
Public Sub jokenresult()
If list.Items.Count > 0 Then
list.Show()
myPlayer.Width = 577
statresult.Text = list.Items.Count & " Items"
Else
list.Hide()
myPlayer.Width = 787
End If
End Sub
[/vb]
Next we will add functionality to the one sub menu items under libraries the Music. To do this just simply double click the Music sub menu.
Then you will be redirected to source code view and add this code so it should now look like as shown below.
[vb]
Private Sub MusicToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MusicToolStripMenuItem.Click
Try
'it will open the folder dialog where you can select where is the specific folder of your music
FolderBrowserDialog1.ShowDialog()
If DialogResult.OK Then
'if true that if you click ok on the folder dialog box then
'it will get the selected path of your folder and store it into di variable
Dim di As New IO.DirectoryInfo(FolderBrowserDialog1.SelectedPath)
'in this line of code it will get all the specific file that has the .mp3 extension and store it into diar1 variable
Dim diar1 As IO.FileInfo() = di.GetFiles("*.mp3")
Dim dra As IO.FileInfo
'and in this line it will gather all information with regardsto fullpath and names of all files and store it to the folderpath variable
folderpath = di.FullName.ToString
list.Items.Clear()
' list the names of all files in the specified directory
For Each dra In diar1
Dim a As Integer = 0
' a = a + 1
list.Items.Add(dra)
Next
'it will call the sub procedure jokenresult() to perform some actions
jokenresult()
End If
Catch ex As Exception
'if errors occur then the program will catch it and send it back to the user.
MsgBox(ex.Message, MsgBoxStyle.Information)
End Try
End Sub
[/vb]
And this is the sample running program playing a selected music.
And this is the sample running program playing a selected Movie.
And finally this is all of the source code.
[vb]
'Description: Personal Media Player that enables user to play Music,Video and pictures etc...
'Author: Joken Villanueva
'Date Created:March 23, 2011
'Modified By:
Public Class mainFrm
Dim folderpath As String
Private Sub MusicToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MusicToolStripMenuItem.Click
Try
'it will open the folder dialog where you can select where is the specific folder of your music
FolderBrowserDialog1.ShowDialog()
If DialogResult.OK Then
'if true that if you click ok on the folder dialog box then
'it will get the selected path of your folder and store it into di variable
Dim di As New IO.DirectoryInfo(FolderBrowserDialog1.SelectedPath)
'in this line of code it will get all the specific file that has the .mp3 extension and store it into diar1 variable
Dim diar1 As IO.FileInfo() = di.GetFiles("*.mp3")
Dim dra As IO.FileInfo
'and in this line it will gather all information with regardsto fullpath and names of all files and store it to the folderpath variable
folderpath = di.FullName.ToString
list.Items.Clear()
' list the names of all files in the specified directory
For Each dra In diar1
Dim a As Integer = 0
' a = a + 1
list.Items.Add(dra)
Next
'it will call the sub procedure jokenresult() to perform some actions
jokenresult()
End If
Catch ex As Exception
'if errors occur then the program will catch it and send it back to the user.
MsgBox(ex.Message, MsgBoxStyle.Information)
End Try
End Sub
Public Sub jokenresult()
If list.Items.Count > 0 Then
list.Show()
myPlayer.Width = 577
statresult.Text = list.Items.Count & " Items"
Else
list.Hide()
myPlayer.Width = 787
End If
End Sub
Private Sub list_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles list.SelectedIndexChanged
'the myPlayer will play or display something from the list based on the user selected item
myPlayer.URL = folderpath & "\" & list.SelectedItem.ToString
End Sub
Private Sub VideosToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles VideosToolStripMenuItem.Click
Try
FolderBrowserDialog1.ShowDialog()
If DialogResult.OK Then
Dim di As New IO.DirectoryInfo(FolderBrowserDialog1.SelectedPath)
Dim diar1 As IO.FileInfo() = di.GetFiles("*.*")
Dim dra As IO.FileInfo
folderpath = di.FullName.ToString
list.Items.Clear()
For Each dra In diar1
list.Items.Add(dra)
Next
jokenresult()
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Information)
End Try
MsgBox(folderpath)
End Sub
Private Sub ImagesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ImagesToolStripMenuItem.Click
Try
FolderBrowserDialog1.ShowDialog()
If DialogResult.OK Then
Dim di As New IO.DirectoryInfo(FolderBrowserDialog1.SelectedPath)
Dim diar1 As IO.FileInfo() = di.GetFiles("*.jpg")
Dim dra As IO.FileInfo
folderpath = di.FullName.ToString
list.Items.Clear()
For Each dra In diar1
list.Items.Add(dra)
Next
jokenresult()
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Information)
End Try
End Sub
Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
Me.Close()
End Sub
Private Sub PlaylistEditorToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PlaylistEditorToolStripMenuItem.Click
'in this line if the playlist editor is click then the list will sho on the form.
If PlaylistEditorToolStripMenuItem.Checked = True Then
list.Show()
myPlayer.Width = 577
Else
list.Hide()
myPlayer.Width = 787
End If
End Sub
Private Sub mainFrm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
list.Items.Clear() ' clear all currect content of the list
list.Hide() ' it will hide the on the main form
myPlayer.Width = 787 ' it will resize the width of myPlayer into 787
End Sub
End Class
[/vb]
You can download the source Code here.Mediaplayer
Readers might read also:
- How to create a Quick Search using VB.net and MS Access
- How to Load data from DatagridView to Textfield
- How to Read an Excel file using Visual Basic.Net