Create a Modern VB MP3 Player UI with WinForms

Lightweight VB MP3 Player — Source Code and FeaturesBuilding a lightweight MP3 player in Visual Basic (VB) is a practical way to learn Windows desktop development, audio playback fundamentals, and basic UI design. This article walks through a compact, easy-to-understand VB MP3 player project: its goals, core features, architecture, required libraries, sample source code, and suggestions for extensions. The focus is on clarity and portability: the player should be small, responsive, and easy to adapt.


Goals and design principles

  • Keep it lightweight: minimal dependencies, small binary size, and low memory/cpu use.
  • Readable source: well-commented, idiomatic VB code so beginners can follow.
  • Essential features first: playback controls, basic playlist handling, and metadata display.
  • Extensible architecture: separate UI, playback engine, and data/playlist logic.

Required tools and libraries

  • Visual Studio (any recent version supporting VB.NET).
  • .NET Framework 4.6+ or .NET ⁄6+ (depending on target).
  • An audio playback library: options include:
    • Windows Media Player COM control (built-in, simple).
    • NAudio (.NET library, more control and modern).
  • Optional: TagLib# for ID3 metadata reading.

For the smallest dependency footprint, using the Windows Media Player COM control avoids adding external DLLs; for more control (gapless playback, formats, mixing), use NAudio.


Project structure

  • MainForm.vb — UI and event handlers.
  • PlayerEngine.vb — playback wrapper (WMP or NAudio).
  • PlaylistManager.vb — load/save and manage playlist entries.
  • MetadataHelper.vb — read ID3 tags (TagLib#) or fallback to filename.
  • Resources — icons and small images.

Core features

  • Play / Pause / Stop controls.
  • Next / Previous track.
  • Seek bar with current time and duration.
  • Simple playlist: add files, remove, save/load M3U.
  • Display basic metadata: Title, Artist, Album, Duration.
  • Volume control and mute.
  • Minimal UI: compact, resizable window, drag-and-drop support.

Minimal example using Windows Media Player COM control

Below is a compact, self-contained example showing essential pieces: a form with WMP control, basic playback controls, playlist handling, and metadata display. This example assumes you added the Windows Media Player COM component to the Toolbox (references: WMPLib).

' MainForm.vb Imports WMPLib Imports System.IO Public Class MainForm     Private WithEvents wmp As New WindowsMediaPlayer()     Private playlist As New List(Of String)     Private currentIndex As Integer = -1     Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load         Me.Text = "Lightweight VB MP3 Player"         TrackBarVolume.Value = 80         wmp.settings.volume = TrackBarVolume.Value         UpdateUI()     End Sub     Private Sub BtnAdd_Click(sender As Object, e As EventArgs) Handles BtnAdd.Click         Using ofd As New OpenFileDialog()             ofd.Filter = "MP3 files|*.mp3|All files|*.*"             ofd.Multiselect = True             If ofd.ShowDialog() = DialogResult.OK Then                 playlist.AddRange(ofd.FileNames)                 If currentIndex = -1 AndAlso playlist.Count > 0 Then                     currentIndex = 0                     PlayCurrent()                 End If                 RefreshPlaylistList()             End If         End Using     End Sub     Private Sub PlayCurrent()         If currentIndex < 0 OrElse currentIndex >= playlist.Count Then Return         Dim path = playlist(currentIndex)         wmp.URL = path         wmp.controls.play()         UpdateMetadataDisplay(path)         UpdateUI()     End Sub     Private Sub BtnPlay_Click(sender As Object, e As EventArgs) Handles BtnPlay.Click         If currentIndex = -1 AndAlso playlist.Count > 0 Then currentIndex = 0         If currentIndex = -1 Then Return         wmp.controls.play()         UpdateUI()     End Sub     Private Sub BtnPause_Click(sender As Object, e As EventArgs) Handles BtnPause.Click         wmp.controls.pause()         UpdateUI()     End Sub     Private Sub BtnStop_Click(sender As Object, e As EventArgs) Handles BtnStop.Click         wmp.controls.stop()         UpdateUI()     End Sub     Private Sub BtnNext_Click(sender As Object, e As EventArgs) Handles BtnNext.Click         If playlist.Count = 0 Then Return         currentIndex = (currentIndex + 1) Mod playlist.Count         PlayCurrent()     End Sub     Private Sub BtnPrev_Click(sender As Object, e As EventArgs) Handles BtnPrev.Click         If playlist.Count = 0 Then Return         currentIndex = (currentIndex - 1 + playlist.Count) Mod playlist.Count         PlayCurrent()     End Sub     Private Sub TrackBarVolume_Scroll(sender As Object, e As EventArgs) Handles TrackBarVolume.Scroll         wmp.settings.volume = TrackBarVolume.Value     End Sub     Private Sub TimerPosition_Tick(sender As Object, e As EventArgs) Handles TimerPosition.Tick         If wmp.currentMedia IsNot Nothing Then             ProgressBarPosition.Maximum = CInt(Math.Max(1, wmp.currentMedia.duration))             ProgressBarPosition.Value = CInt(Math.Min(ProgressBarPosition.Maximum, Math.Round(wmp.controls.currentPosition)))             LabelTime.Text = $"{FormatTime(wmp.controls.currentPosition)} / {FormatTime(wmp.currentMedia.duration)}"         Else             ProgressBarPosition.Value = 0             LabelTime.Text = "00:00 / 00:00"         End If     End Sub     Private Sub ProgressBarPosition_MouseDown(sender As Object, e As MouseEventArgs) Handles ProgressBarPosition.MouseDown         If wmp.currentMedia Is Nothing Then Return         Dim pct = e.X / ProgressBarPosition.Width         Dim pos = pct * wmp.currentMedia.duration         wmp.controls.currentPosition = pos     End Sub     Private Sub wmp_PlayStateChange(NewState As Integer) Handles wmp.PlayStateChange         ' 8 = MediaEnded         If NewState = 8 Then             BtnNext.PerformClick()         End If         UpdateUI()     End Sub     Private Sub RefreshPlaylistList()         ListBoxPlaylist.Items.Clear()         For Each p In playlist             ListBoxPlaylist.Items.Add(Path.GetFileNameWithoutExtension(p))         Next     End Sub     Private Sub UpdateMetadataDisplay(path As String)         Try             Dim tag = TagLib.File.Create(path)             LabelTitle.Text = If(String.IsNullOrEmpty(tag.Tag.Title), Path.GetFileNameWithoutExtension(path), tag.Tag.Title)             LabelArtist.Text = If(tag.Tag.FirstPerformer, tag.Tag.FirstPerformer, "")             LabelAlbum.Text = If(tag.Tag.Album, tag.Tag.Album, "")         Catch ex As Exception             LabelTitle.Text = Path.GetFileNameWithoutExtension(path)             LabelArtist.Text = ""             LabelAlbum.Text = ""         End Try     End Sub     Private Function FormatTime(seconds As Double) As String         Dim t = TimeSpan.FromSeconds(seconds)         Return t.ToString("mm:ss")     End Function     Private Sub UpdateUI()         BtnPlay.Enabled = (playlist.Count > 0)         BtnPause.Enabled = (playlist.Count > 0)         BtnStop.Enabled = (playlist.Count > 0)         LabelStatus.Text = If(wmp.playState = WMPPlayState.wmppsPlaying, "Playing", If(wmp.playState = WMPPlayState.wmppsPaused, "Paused", "Stopped"))     End Sub End Class 

Notes:

  • Add controls named BtnAdd, BtnPlay, BtnPause, BtnStop, BtnNext, BtnPrev, TrackBarVolume, ProgressBarPosition, LabelTime, LabelTitle, LabelArtist, LabelAlbum, ListBoxPlaylist, TimerPosition, LabelStatus on the form.
  • This uses TagLib# (TagLib.File.Create) only if you add TagLib# to the project; otherwise remove the metadata code or use wmp.currentMedia.getItemInfo.

Playlist persistence (M3U)

Simple routines to save/load a playlist as M3U:

' PlaylistManager.vb Imports System.IO Public Module PlaylistManager     Public Sub SaveM3U(path As String, items As List(Of String))         Using sw As New StreamWriter(path, False, System.Text.Encoding.UTF8)             sw.WriteLine("#EXTM3U")             For Each f In items                 sw.WriteLine(f)             Next         End Using     End Sub     Public Function LoadM3U(path As String) As List(Of String)         Dim out As New List(Of String)         For Each line In File.ReadAllLines(path)             If String.IsNullOrWhiteSpace(line) Then Continue For             If line.StartsWith("#") Then Continue For             out.Add(line.Trim())         Next         Return out     End Function End Module 

Using NAudio (alternative playback engine)

NAudio offers finer control and supports additional scenarios (wave mixing, decoding). For MP3 playback you’ll typically use MediaFoundationReader or Mp3FileReader + WaveOutEvent. Example:

' PlayerEngine.vb (NAudio) Imports NAudio.Wave Public Class PlayerEngineNA     Private waveOut As WaveOutEvent     Private reader As MediaFoundationReader ' or Mp3FileReader     Public Sub PlayFile(path As String)         Stop()         reader = New MediaFoundationReader(path)         waveOut = New WaveOutEvent()         waveOut.Init(reader)         waveOut.Play()     End Sub     Public Sub Stop()         If waveOut IsNot Nothing Then             waveOut.Stop()             waveOut.Dispose()             waveOut = Nothing         End If         If reader IsNot Nothing Then             reader.Dispose()             reader = Nothing         End If     End Sub     Public Sub Pause()         If waveOut IsNot Nothing Then waveOut.Pause()     End Sub     Public Sub Resume()         If waveOut IsNot Nothing Then waveOut.Play()     End Sub     Public Property Volume As Single         Get             Return If(waveOut IsNot Nothing, waveOut.Volume, 1.0F)         End Get         Set(value As Single)             If waveOut IsNot Nothing Then waveOut.Volume = value         End Set     End Property End Class 

UI/UX suggestions

  • Keep the main window compact with optional expanded view for playlist and metadata.
  • Support drag-and-drop onto the playlist area.
  • Keyboard shortcuts: Space = Play/Pause, Left/Right = Prev/Next, Up/Down = Volume.
  • Offer light/dark themes and small album art display.
  • Allow saving window size/last playlist between sessions.

Performance and portability tips

  • Avoid heavy UI updates on timers; update UI only when necessary.
  • For large playlists, virtualize the list display.
  • Use asynchronous file IO when scanning directories.
  • If deploying for modern Windows only, prefer .NET ⁄7 and NAudio/MediaFoundation for better codec support.

Extensions and advanced features

  • Gapless playback and crossfade using NAudio mixing.
  • Equalizer presets, visualizer using FFT on audio samples.
  • Internet radio streaming (HTTP streams).
  • Support for additional formats (FLAC, AAC) using Media Foundation or third-party decoders.
  • Portable mode: store config in an INI or JSON alongside executable.

Final notes

This lightweight VB MP3 player pattern is ideal for learning and small utilities. Start with the Windows Media Player control for the fastest results, then migrate to NAudio when you need more control. The sample code above covers essential playback and playlist management while remaining compact and readable — a good base to customize and expand.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *