Custom Playlist Handler in Visual Basic - Part 2 - Playing Playlists

Introduction: This is the second of a two part tutorial on how to create a custom music playlist and player in Visual Basic. Note: Our Visual Basic player will simply use the Windows Media Player control and this series is going to be mainly focusing on the IO. If you're only interested in custom music players, it may save you time by skipping this series. This Tutorial: This part will be covering the loading and playing of playlists. Components: You will want one button to begin the loading process/function, and a Windows Media Player component as well, named 'AxWindowsMediaPlayer1'. To add the component, you may need to add the reference by going to: Project > Add Reference > COM Components > Windows Media Player Imports: First we need to import System.IO to read/write to/from files later on, we do this like so...
  1. Imports System.IO, WMPLib
Loading Playlists: All of this code can go on one simple button click. First we want to allow the user to select a .txt playlist file so we create a new openfiledialog, set the filter and properties and then display. Next we verify that the selected file exists, and read the lines to a new list(of string) named 'lines'. Finally we then want to iterate through each string line in our 'lines' string list, convert each one to the correct object format with the full music path, and add it to a new playlist of the correct object type for the windows media player playlist. We then set the current playist to the newly created playlist, it will automatically begin to play.
  1. Private Function loadPlaylist()
  2. Dim username As String = Environ("username")
  3. Dim musicPath As String = "C:\users\" + username + "\music"
  4. Dim Playlist As IWMPPlaylist = AxWindowsMediaPlayer1.playlistCollection.newPlaylist("thePlaylist")
  5. Dim path As String = Nothing
  6. Using fo As New OpenFileDialog
  7. fo.Filter = "Text Files | *.txt"
  8. fo.FilterIndex = 1
  9. fo.RestoreDirectory = True
  10. fo.Multiselect = False
  11. fo.ShowDialog()
  12. path = fo.FileName
  13. End Using
  14. Dim lines As New List(Of String)
  15. Using sr As New StreamReader(path)
  16. While (sr.Peek <> -1)
  17. lines.Add(sr.ReadLine())
  18. End While
  19. End Using
  20. For Each FilePath As String In lines
  21. Dim VideoFile As WMPLib.IWMPMedia3 = AxWindowsMediaPlayer1.newMedia(musicPath + FilePath)
  22. Playlist.appendItem(VideoFile)
  23. Next
  24. AxWindowsMediaPlayer1.currentPlaylist = Playlist
  25. End Function
Running the Function: On the button click we simply call the function...
  1. Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
  2. loadPlaylist()
  3. End Sub

Add new comment