A simple media player program in C# .NET 4.0

This is a program sample that you should go through at the intermediate level of your knowledge about the .Net platform by Microsoft. The entire program is written in C#, you may also use VB.NET if you are familiar with it. The logic behind the program is same, just coding syntax will vary. Well, all the best! let’s start with a quick glance at our objective :

i. We shall construct a media player.
ii. It shall be capable of playing media files of any kind, say a music file of .mp3 or .ogg format, a picture of .jpg or .png format as well as a video file of .wmv or .avi format.
iii. We shall be able to add files, play them, pause them and stop them.
For, our purpose we will use WPF(Windows Presentation Foundation) standard form in Visual Studio 2010 edition.

STEPS:

1. Create New Project.
2. Choose WPF, give a project name and add it. A workspace is created with a default Form loaded with the XAML code engraved in it.
3. Open toolbox and choose rather drag and drop a media element on the workspace.
4. Add 4 buttons name them as ‘PLAY’,’PAUSE’,STOP’,’ADD MEDIA’ respectively and a textbox to display the filename being played. A screenshot is given below:

Screenshot of basic layout of WPF form.

5. Double-click on ‘ADD MEDIA’ button and it shall take you to the MainWindow.xaml.cs file where we write our code. Now, a default method is called as we are double clicking the ‘button4’(just an index), that is, button4_click. Now I shall write the entire code.

using system;
using system.LINQ;
using System.Text;
using System.Windows.Forms;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
 
namespace mediaplayer
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
 
        
        private void button4_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.AddExtension = true;
            ofd.DefaultExt = "*.*";
            ofd.Filter = "Media(*.*)|*.*";
            ofd.ShowDialog();
            mediaElement1.MediaOpened += new RoutedEventHandler(mediaElement1_MediaOpened);
            mediaElement1.Source = new Uri(ofd.FileName);
        }
        
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            
            mediaElement1.Play();
        }
        
        private void button3_Click(object sender, RoutedEventArgs e)
        {
            mediaElement1.Stop();
        }
 
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            mediaElement1.Pause();
            
        }
 
        void mediaElement1_MediaOpened(object sender, RoutedEventArgs e)
        {
            label1.Content = mediaElement1.Source.ToString();
        }
    }
}
6. Press CTRL+F5 for the code to run. And there you go! Click on ‘Add Media’ button and choose media and watch it play!

Enjoy! Have Fun!

This link might be useful for you: http://www.youtube.com/watch?v=f_bBWHCoKpk

45 thoughts on “A simple media player program in C# .NET 4.0

  1. Thanks for your code! but it faces with an error >> “Can’t load media unless LoadBehaviour or UnloadedBehaviour is set to manual”
    How shall I handle the “Unloaded” event that it play the video ?

  2. The type or namespace name ‘OpenFileDialog’ could not be found (are you missing a using directive or an assembly reference?) C:\Users\user\Documents\Visual Studio 2008\Projects\mediaplayer\mediaplayer\Window1.xaml.cs this the error i encountered after turning the loadedbehavior to manual

    1. Use these references:

      using System.Windows.Input;
      using System.Windows.Media;
      using System.Windows.Media.Imaging;

      Else the OpenFileDialog won’t work.

    2. Just right click on the OpenFileDialog from the popup goto – resolve–>using Microsoft.Win32; select it , this will add the reference of OpenFileDialog.
      Hope this will work for you.

  3. mediaElement1.MediaOpened += new RoutedEventHandler(mediaElemen

    In the Above Line U are asking for an EVENT but, i can’t find any.

    And, Loaded Behavior is not in action.
    // What To doo..

    1. That’ll be “mediaElement1.MediaOpened += new RoutedEventHandler(mediaElement1)”. Set Loaded Behaviour to “manual” in properties for MediaElement.
      Do watch the video also.

  4. The type or namespace name ‘Forms’ does not exist in the namespace ‘System.Windows’ (are you missing an assembly reference?

  5. Error 2 The type or namespace name ‘OpenFileDialog’ could not be found (are you missing a using directive or an assembly reference?) c:\users\hafiz\documents\visual studio 2012\Projects\WpfMEDIA\WpfMEDIA\MainWindow.xaml.cs 53 38 WpfMEDIA
    what sall i do ?

  6. In Win XP he same code doesnot work .Is there any specific video file format we have to give.I am not getting any kind of error but some how its not loading the video.

    1. Are you sure that you’re using .NET 4.0? And it loads all formats for which you have a suitable codec for. Maybe .mkv or .mov will be a problem in XP but else it’d run absolutely fine.

      1. Yes I am using .net 4.0.I tried with .3gp format video also.the problem is still the same.

  7. MediaElement1.MediaOpend+=new RoutedEventhandler(MediaElement1_MediaOpend);
    In above line”MediaElement_MediaOpened” does not exist in the current context

    What i doooo??????

    1. the particular event ‘media_opened’ has been deleted from the .cs file but the media element 1 still has it. so, go to xaml view and click on media element 1 and delete the mediaopened event call from there.

    1. private void button1_Click(object sender, RoutedEventArgs e)
      {
      mediaElement1.LoadedBehavior = MediaState.Play;
      }

      private void btnPause_Click(object sender, RoutedEventArgs e)
      {

      mediaElement1.LoadedBehavior = MediaState.Pause;
      }

      private void btnStop_Click(object sender, RoutedEventArgs e)
      {
      mediaElement1.LoadedBehavior = MediaState.Stop;

      }

  8. please help me some error is display for this line
    mediaElement1.MediaOpened += new RoutedEventHandler(mediaElement1.MediaOpened);

    ERROR:
    Error 1 The event ‘System.Windows.Controls.MediaElement.MediaOpened’ can only appear on the left hand side of += or -=

    please help me how to solve the problem……..

  9. hi,
    my media player play media files well,thanks for share your knowledge with world,
    but in this code you use play(),pause() & stop() methods,that is not working….
    media files play but can’t respond on play,pause and stop button,
    plz check what is missing?
    thanks for this post…Awesome

      1. private void button1_Click(object sender, RoutedEventArgs e)
        {
        mediaElement1.LoadedBehavior = MediaState.Play;
        }
        private void btnPause_Click(object sender, RoutedEventArgs e)
        {
        mediaElement1.LoadedBehavior = MediaState.Pause;
        }
        private void btnStop_Click(object sender, RoutedEventArgs e)
        {
        mediaElement1.LoadedBehavior = MediaState.Stop;
        }

  10. media element plays some videos with distortion, has some kind of green layering over it. The same video works fine in windows media player. Any documentation you can point me towards?

  11. I need to show only the name of the music or video playing, in the textbox and when playing a .mp3 file i need to play a visualizer effect in the media element what can I do to accomplish these

  12. Hi this is anjireddy nice article….. i want more information about video player Like Screenshot of basic layout of WPF form. more screenshots ..if it possible give me please.

Leave a reply to Abhix Cancel reply