Search code examples
c#.netwpfaudiomediaelement

How to play a sound in WPF


I'm a novice C# programmer and am having trouble getting music to play in my WPF (Windows) application using VS 2008. This is a web app. What I think is happening is myMediaElementExample variable is empty at the time it is used to execute the Play method in the ExpenseReportPage.xaml.cs file.

Right now this program builds, but after I run it, it encounters an exception at the myMediaElementExample.Play(); line. The exception says:

An unhandled win32 exception occurred in the WpfApplication1.vhost.exe [948].

Can any of you give me tips on what else I might try? I've only included the code relevant to this problem:

ExpenseReportPage.xaml.cs file:

namespace ExpenseIt
{
    public partial class ExpenseReportPage : Page
    {
...    }

    public partial class MediaElementExample : Page
    {
        MediaElement myMediaElementExample = new MediaElement();

        public MediaElementExample()
        {
         }

        public void OnMouseDownPlayMedia(object sender, RoutedEventArgs args) //MouseButtonEventArgs
        {
            // The Play method will begin the media if it is not currently active or 
            // resume media if it is paused. This has no effect if the media is
            // already running.
            myMediaElementExample.Play();
        }
    }
}

HomePage.xaml.cs file:

namespace ExpenseIt
{
    public partial class HomePage : Page
    {
        MediaElementExample mediaElementExample = new MediaElementExample();

        public HomePage()
        {
            InitializeComponent();
        }        
        void HandleClick(object sender, RoutedEventArgs e) 
            {
                Button srcButton = e.Source as Button;
                srcButton.Width = 200;
                mediaElementExample.OnMouseDownPlayMedia(sender, e);
            }
    }
}

Solution

  • For debugging purposes surround the line:

    myMediaElementExample.Play();
    

    with a try{} catch{} block:

    try
    {
        myMediaElementExample.Play();
    }
    catch (Exception ex)
    {
        // Either print out the exception or examine it in the debugger.
    }
    

    This will give you more information on what's causing the exception. If it's still unclear update the question with this new information.

    If myMediaElementExample was null then I'd expect that you'd get a System.NullReferenceException rather than the win32 one you're seeing. You can check this by setting a break point on the myMediaElementExample.Play(); line and examining it.

    Once you've found and fixed the problem you could remove the exception handler or if you want to be cautious leave it in, but only trap the exceptions that MediaElement.Play raises.