Skip to main content

WPF C#/VB
Media Player with File Metadata

C#

// AZUL CODING ---------------------------------------
// WPF C#/VB - Media Player with File Metadata
// https://youtu.be/jARmuKSRsio


using System;
using System.Windows;
using System.IO;
using System.Windows.Threading;
using System.Text;
using Microsoft.Win32;

namespace AzulMediaPlayer
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private bool IsPlaying = false;
        private bool IsUserDraggingSlider = false;

        private readonly DispatcherTimer Timer = new() { Interval = TimeSpan.FromSeconds(0.1) };
        private readonly OpenFileDialog MediaOpenDialog = new()
        {
            Title = "Open a media file",
            Filter = "Media Files (*.mp3,*.mp4)|*.mp3;*.mp4"
        };

        public MainWindow()
        {
            InitializeComponent();

            Timer.Tick += Timer_Tick;
            Timer.Start();
        }

        private void Timer_Tick(object? sender, EventArgs e)
        {
            if (Player.Source != null && Player.NaturalDuration.HasTimeSpan && !IsUserDraggingSlider)
            {
                ProgressSlider.Maximum = Player.NaturalDuration.TimeSpan.TotalSeconds;
                ProgressSlider.Value = Player.Position.TotalSeconds;
            }
        }

        private void OpenBtn_Click(object sender, RoutedEventArgs e)
        {
            if (MediaOpenDialog.ShowDialog() == true)
            {
                Player.Source = new Uri(MediaOpenDialog.FileName);
                TitleLbl.Content = Path.GetFileName(MediaOpenDialog.FileName);

                Player.Play();
                IsPlaying = true;
            }
        }

        #region Media Controls

        private void PlayBtn_Click(object sender, RoutedEventArgs e)
        {
            if (Player?.Source != null)
            {
                Player.Play();
                IsPlaying = true;
            }
        }

        private void PauseBtn_Click(object sender, RoutedEventArgs e)
        {
            if (IsPlaying)
                Player.Pause();
        }

        private void StopBtn_Click(object sender, RoutedEventArgs e)
        {
            if (IsPlaying)
            {
                Player.Stop();
                IsPlaying = false;
            }
        }

        private void ProgressSlider_DragStarted(object sender, System.Windows.Controls.Primitives.DragStartedEventArgs e)
        {
            IsUserDraggingSlider = true;
        }

        private void ProgressSlider_DragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e)
        {
            IsUserDraggingSlider = false;
            Player.Position = TimeSpan.FromSeconds(ProgressSlider.Value);
        }

        private void ProgressSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            StatusLbl.Text = TimeSpan.FromSeconds(ProgressSlider.Value).ToString(@"hh\:mm\:ss");
        }

        #endregion
        #region Properties

        private void PropertiesBtn_Click(object sender, RoutedEventArgs e)
        {
            if (MediaOpenDialog.FileName != "")
            {
                var tfile = TagLib.File.Create(MediaOpenDialog.FileName);
                StringBuilder sb = new();

                sb.AppendLine("Duration: " + tfile.Properties.Duration.ToString(@"hh\:mm\:ss"));

                if (tfile.Properties.MediaTypes.HasFlag(TagLib.MediaTypes.Audio))
                {
                    sb.AppendLine("Audio bitrate: " + tfile.Properties.AudioBitrate);
                    sb.AppendLine("Audio sample rate: " + tfile.Properties.AudioSampleRate);
                    sb.AppendLine("Audio channels: " + (tfile.Properties.AudioChannels == 1 ? "Mono" : "Stereo"));
                }

                if (tfile.Properties.MediaTypes.HasFlag(TagLib.MediaTypes.Video))
                {
                    sb.AppendLine($"Video resolution: {tfile.Properties.VideoWidth} x {tfile.Properties.VideoHeight}");
                }

                MessageBox.Show(sb.ToString(), "Properties");
            }
        }

        #endregion
    }
}

Enjoying this tutorial?


VB.NET

' AZUL CODING ---------------------------------------
' WPF C#/VB - Media Player with File Metadata
' https://youtu.be/jARmuKSRsio


Imports Microsoft.Win32
Imports System.Text
Imports System.Windows.Threading

Class MainWindow
    Private IsPlaying As Boolean = False
    Private IsUserDraggingSlider As Boolean = False

    Private ReadOnly Timer As DispatcherTimer = New DispatcherTimer() With {
        .Interval = TimeSpan.FromSeconds(0.1)
    }
    Private ReadOnly MediaOpenDialog As OpenFileDialog = New OpenFileDialog() With {
        .Title = "Open a media file",
        .Filter = "Media Files (*.mp3,*.mp4)|*.mp3;*.mp4"
    }

    Public Sub New()
        InitializeComponent()
        AddHandler Timer.Tick, AddressOf Timer_Tick
        Timer.Start()
    End Sub

    Private Sub Timer_Tick(sender As Object, e As EventArgs)
        If Player.Source IsNot Nothing AndAlso Player.NaturalDuration.HasTimeSpan AndAlso Not IsUserDraggingSlider Then
            ProgressSlider.Maximum = Player.NaturalDuration.TimeSpan.TotalSeconds
            ProgressSlider.Value = Player.Position.TotalSeconds
        End If
    End Sub

    Private Sub OpenBtn_Click(sender As Object, e As RoutedEventArgs)
        If MediaOpenDialog.ShowDialog() = True Then
            Player.Source = New Uri(MediaOpenDialog.FileName)
            TitleLbl.Content = IO.Path.GetFileName(MediaOpenDialog.FileName)
            Player.Play()
            IsPlaying = True
        End If
    End Sub

    Private Sub PlayBtn_Click(sender As Object, e As RoutedEventArgs)
        If Player?.Source IsNot Nothing Then
            Player.Play()
            IsPlaying = True
        End If
    End Sub

    Private Sub PauseBtn_Click(sender As Object, e As RoutedEventArgs)
        If IsPlaying Then Player.Pause()
    End Sub

    Private Sub StopBtn_Click(sender As Object, e As RoutedEventArgs)
        If IsPlaying Then
            Player.Stop()
            IsPlaying = False
        End If
    End Sub

    Private Sub ProgressSlider_DragStarted(sender As Object, e As Primitives.DragStartedEventArgs)
        IsUserDraggingSlider = True
    End Sub

    Private Sub ProgressSlider_DragCompleted(sender As Object, e As Primitives.DragCompletedEventArgs)
        IsUserDraggingSlider = False
        Player.Position = TimeSpan.FromSeconds(ProgressSlider.Value)
    End Sub

    Private Sub ProgressSlider_ValueChanged(sender As Object, e As RoutedPropertyChangedEventArgs(Of Double))
        StatusLbl.Text = TimeSpan.FromSeconds(ProgressSlider.Value).ToString("hh\:mm\:ss")
    End Sub

    Private Sub PropertiesBtn_Click(sender As Object, e As RoutedEventArgs)
        If MediaOpenDialog.FileName <> "" Then
            Dim tfile = TagLib.File.Create(MediaOpenDialog.FileName)
            Dim sb As StringBuilder = New StringBuilder()
            sb.AppendLine("Duration: " & tfile.Properties.Duration.ToString("hh\:mm\:ss"))

            If tfile.Properties.MediaTypes.HasFlag(TagLib.MediaTypes.Audio) Then
                sb.AppendLine("Audio bitrate: " & tfile.Properties.AudioBitrate)
                sb.AppendLine("Audio sample rate: " & tfile.Properties.AudioSampleRate)
                sb.AppendLine("Audio channels: " & If(tfile.Properties.AudioChannels = 1, "Mono", "Stereo"))
            End If

            If tfile.Properties.MediaTypes.HasFlag(TagLib.MediaTypes.Video) Then
                sb.AppendLine($"Video resolution: {tfile.Properties.VideoWidth} x {tfile.Properties.VideoHeight}")
            End If

            MessageBox.Show(sb.ToString(), "Properties")
        End If
    End Sub
End Class

XAML

<!-- AZUL CODING --------------------------------------- -->
<!-- WPF C#/VB - Media Player with File Metadata -->
<!-- https://youtu.be/jARmuKSRsio -->


<Window x:Class="AzulMediaPlayer.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="Azul Coding Media Player" Width="500" SizeToContent="Height" ResizeMode="CanMinimize">
    <StackPanel Background="White">
        <Label x:Name="TitleLbl" Content="Media player" Padding="5,0,5,5" Margin="20" FontWeight="SemiBold" FontSize="16" BorderBrush="DodgerBlue" BorderThickness="0,0,0,2"/>
        <MediaElement x:Name="Player" LoadedBehavior="Manual" Stretch="None" Height="225" Margin="20,0"/>
        <DockPanel Margin="20">
            <Button Name="OpenBtn" Click="OpenBtn_Click" Padding="5" Margin="0,0,10,0" Background="#f0f0f0">
                <StackPanel Orientation="Horizontal" VerticalAlignment="Center">
                    <Image Height="24" Width="24" Source="https://img.icons8.com/fluency/48/opened-folder.png"/>
                </StackPanel>
            </Button>
            <Button Name="PlayBtn" Click="PlayBtn_Click" Padding="5" Margin="0,0,10,0" Background="#f0f0f0">
                <StackPanel Orientation="Horizontal" VerticalAlignment="Center">
                    <Image Height="24" Width="24" Source="https://img.icons8.com/fluency/48/play.png"/>
                </StackPanel>
            </Button>
            <Button Name="PauseBtn" Click="PauseBtn_Click" Padding="5" Margin="0,0,10,0" Background="#f0f0f0">
                <StackPanel Orientation="Horizontal" VerticalAlignment="Center">
                    <Image Height="24" Width="24" Source="https://img.icons8.com/fluency/48/pause.png"/>
                </StackPanel>
            </Button>
            <Button Name="StopBtn" Click="StopBtn_Click" Padding="5" Margin="0,0,10,0" Background="#f0f0f0">
                <StackPanel Orientation="Horizontal" VerticalAlignment="Center">
                    <Image Height="24" Width="24" Source="https://img.icons8.com/fluency/48/stop.png"/>
                </StackPanel>
            </Button>
            <Button Name="PropertiesBtn" Click="PropertiesBtn_Click" Padding="5" Margin="0,0,10,0" Background="#f0f0f0">
                <StackPanel Orientation="Horizontal" VerticalAlignment="Center">
                    <Image Height="24" Width="24" Source="https://img.icons8.com/fluency/48/info.png"/>
                </StackPanel>
            </Button>
            <TextBlock Name="StatusLbl" FontSize="14" VerticalAlignment="Center" Margin="10,0" MinWidth="60" TextAlignment="Center">00:00:00</TextBlock>
            <Slider Name="ProgressSlider" Maximum="1" Thumb.DragStarted="ProgressSlider_DragStarted" Thumb.DragCompleted="ProgressSlider_DragCompleted" ValueChanged="ProgressSlider_ValueChanged" VerticalAlignment="Center"/>
        </DockPanel>
    </StackPanel>
</Window>