#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.

Advertisements