title: How to play a sound in WPF
body: <p>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 <code>myMediaElementExample</code> variable is empty at the time it is used to execute the <code>Play</code> method in the <code>ExpenseReportPage.xaml.cs</code> file. </p>
  
  <p>Right now this program builds, but after I run it, it encounters an exception at the <code>myMediaElementExample.Play();</code> line.  The exception says:</p>
  
  <pre><code>An unhandled win32 exception occurred in the WpfApplication1.vhost.exe [948].
  </code></pre>
  
  <p>Can any of you give me tips on what else I might try?  I've only included the code relevant to this problem:</p>
  
  <p>ExpenseReportPage.xaml.cs file:</p>
  
  <pre><code>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();
          }
      }
  }
  </code></pre>
  
  <p>HomePage.xaml.cs file:</p>
  
  <pre><code>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);
              }
      }
  }
  </code></pre>