Custom Media Player in WPF (Part 1)





4.00/5 (2 votes)
Custom media player in WPF (Part 1)
Introduction
First of all, I would like to welcome everyone to my new blog and wish you all a happy new year… Through this blog, I hope I can provide help, tips and
some useful information about common problems we’ve all faced in programming, as well as some sample applications...
In my first post, I’m going to
show you how you can easily create your own custom Media Player which can automatically search for lyrics for the song you’re listening to.
To begin, we are going to create a new WPF application (in this demo, I am going to use the .NET 4 Framework and Visual Studio 2010, but most of the functions mentioned in this post are also available on .NET 3.5).
The next thing we are going to do is to add 4 buttons and a mediaElement
to
our MainWindow
by dragging them from the toolbox we have available here. These 4 buttons cover the main 4 functions of a media player, play, pause, stop, open. I am not going to
give you any instructions on how to “reshape” them as I believe the best GUI is the one you make yourself, so this is up to you.
Let’s open
the MainWindow.xaml.cs file now and create the play
, pause
and stop
functions.
bool fileIsPlaying;
//play the file
private void playButton__Click(object sender, RoutedEventArgs e)
{
mediaElement.Play();
fileIsPlaying = true;
}
//pause the file
private void pauseButton_Click(object sender, RoutedEventArgs e)
{
mediaElement.Pause();
fileIsPlaying = false;
}
//stop the file
private void stopButton_Click(object sender, RoutedEventArgs e)
{
mediaElement.Stop();
fileIsPlaying = false;
}
The code behind the open button is a little bit more complex.
private void openFileButton_Click(object sender, RoutedEventArgs e)
{
Stream checkStream = null;
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "All Supported File Types
(*.mp3,*.wav,*.mpeg,*.wmv,*.avi)|*.mp3;*.wav;*.mpeg;*.wmv;*.avi";
// Show open file dialog box
if ((bool)dlg.ShowDialog())
{
try
{
// check if something is selected
if ((checkStream = dlg.OpenFile()) != null)
{
mediaElement.Source = new Uri(dlg.FileName);
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
You can easily change the file types allowed by users in the OpenFileDialog just by changing this value.
dlg.Filter = "All Supported File Types
(*.mp3,*.wav,*.mpeg,*.wmv,*.avi)|*.mp3;*.wav;*.mpeg;*.wmv;*.avi";
You can also create 2 sliders in order to control the volume and the speed ratio of the playback. You should add these properties into your XAML file:
For the
speedRatioSlider
:
Value="1" Maximum="3" SmallChange="0.25"
For the
volumeSlider
:
Value="0.5" Maximum="1"
SmallChange="0.01" LargeChange="0.1"
So now, we’re finally able to edit our C# code and create the events.
//change the speed of the playback
void speedRatioSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
mediaElement.SpeedRatio = speedRatioSlider.Value;
}
//turn volume up-down
private void volumeSlider_ValueChanged
(object sender, RoutedPropertyChangedEventArgs<double> e)
{
mediaElement.Volume = volumeSlider.Value;
}
Now there’s one more thing we need to do. We have to create a slide bar attached to this mediaElement
to show the progress
made. For this task, we’re going to need a slider, a progress bar and a Timer to periodically change the values of these elements.
First of all, we
need to create a DispatcherTimer
and an event that will occur every 1 second, in order to change the value of the textbox displaying the current
progress of the playback.
DispatcherTimer timer;
public delegate void timerTick();
timerTick tick;
public MainWindow()
{
InitializeComponent();
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += new EventHandler(timer_Tick);
tick = new timerTick(changeStatus);
}
void timer_Tick(object sender, EventArgs e)
{
Dispatcher.Invoke(tick);
}
We’ll use the Position
property of the mediaElement
(which is, though, available only after the mediaElement_MediaOpened
event
occurs) to change the value of the textbox that displays the current time of the playback.
//visualize progressBar
//the fileIsPlaying variable is true when the media is playing
//and false when the media is paused or stopped
void changeStatus()
{
if (fileIsPlaying)
{
string sec, min, hours;
#region customizeTime
if (mediaElement.Position.Seconds < 10)
sec = "0" + mediaElement.Position.Seconds.ToString();
else
sec = mediaElement.Position.Seconds.ToString();
if (mediaElement.Position.Minutes < 10)
min = "0" + mediaElement.Position.Minutes.ToString();
else
min = mediaElement.Position.Minutes.ToString();
if (mediaElement.Position.Hours < 10)
hours = "0" + mediaElement.Position.Hours.ToString();
else
hours = mediaElement.Position.Hours.ToString();
#endregion customizeTime
seekSlider.Value = mediaElement.Position.TotalMilliseconds;
progressBar.Value = mediaElement.Position.TotalMilliseconds;
if (mediaElement.Position.Hours == 0)
{
currentTimeTextBlock.Text = min + ":" + sec;
}
else
{
currentTimeTextBlock.Text = hours + ":" + min + ":" + sec;
}
}
}
So now, we have the current time displayed on the textbox and the progress of the playback. We have to create the events for the
following functions of the seekSlider
:
//seek to desirable position of the file
//you will also have to set the moveToPosition property of the seekSlider to
//true
private void seekSlider_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
TimeSpan ts = new TimeSpan(0, 0, 0, 0, (int)seekSlider.Value);
changePostion(ts);
}
//mouse down on slide bar in order to seek
private void seekSlider_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
isDragging = true;
}
private void seekSlider_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (isDragging)
{
TimeSpan ts = new TimeSpan(0, 0, 0, 0, (int)seekSlider.Value);
changePostion(ts);
}
isDragging = false;
}
//change position of the file
void changePostion(TimeSpan ts)
{
mediaElement.Position = ts;
}
Finally, we need to implement the mediaElement_MediaOpened
and mediaElement_MediaEnded
functions.
//occurs when the file is opened
public void mediaElement_MediaOpened(object sender, RoutedEventArgs e
{
timer.Start();
fileIsPlaying = true;
openMedia();
}
//opens media,adds file to playlist and gets file info
public void openMedia()
{
......
}
//occurs when the file is done playing
private void mediaElement_MediaEnded(object sender, RoutedEventArgs e)
{
mediaElement.Stop();
volumeSlider.ValueChanged -= new RoutedPropertyChangedEventHandler<double>(volumeSlider_ValueChanged);
speedRatioSlider.ValueChanged -= new RoutedPropertyChangedEventHandler<double>(speedRatioSlider_ValueChanged);
}
That’s all for now…We have created our own, fully functional media player.. You can download the source code here. I would be happy to read any thoughts or suggestions you might have.