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

Advertisement

#8 – Audio and Video

WPF makes it very easy to play audio or video content in your application.  You can play any media type supported by Windows Media Player including audio formats like WAV and MP3 or video formats like AVI, WMV, and MPG.

You play audio and video by including a media UI element directly in your XAML.  This allows rendering and playing video on a wide variety of user controls.  Here’s an example of a video playing on the surface of a Button.

<Button Height="258" HorizontalAlignment="Left" Margin="26,21,0,0" Name="button1" VerticalAlignment="Top" Width="436" >
    <Button.Content>
       <MediaElement Source="C:\Users\Public\Videos\Sample Videos\Wildlife.wmv" Stretch="Fill"/>
    </Button.Content>
</Button>

More Info: MSDN or CodePlex