#698 – Playing an MP3 File Using a MediaPlayer Object

You can use the MediaPlayer class in System.Windows.Media to load and play an MP3 file at runtime.  Here’s an example, where we load and play an MP3 file when the user clicks a button.

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            this.InitializeComponent();
        }

        private MediaPlayer mplayer = new MediaPlayer();

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            mplayer.Open(new Uri(@"D:\Temp\Respect.mp3"));
            mplayer.Play();
        }
    }

Notice that we declare the MediaPlayer object within the class, rather than within the Click event handler.  If we declared the object within the handler, the variable would go out of scope when the handler exited and the MediaPlayer object would then eventually get garbage collected–which would stop playback.  So we need to declare it within the class so that the object lives even after the event handler exits.

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #698 – Playing an MP3 File Using a MediaPlayer Object

  1. Pingback: Dew Drop – November 26, 2012 (#1,449) | Alvin Ashcraft's Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: