如何在WPF中播放声音

sal*_*ere 1 .net c# audio wpf mediaelement

我是新手C#程序员,在使用VS 2008在我的WPF(Windows)应用程序中播放音乐时遇到了麻烦.这是一个Web应用程序.我认为发生的myMediaElementExample变量是在用于执行文件中的Play方法时为空ExpenseReportPage.xaml.cs.

现在这个程序构建,但是在我运行之后,它遇到了一个异常myMediaElementExample.Play();.例外说:

An unhandled win32 exception occurred in the WpfApplication1.vhost.exe [948].
Run Code Online (Sandbox Code Playgroud)

你能不能给我一些关于我可能尝试的其他建议?我只包含了与此问题相关的代码:

ExpenseReportPage.xaml.cs文件:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

HomePage.xaml.cs文件:

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);
            }
    }
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*isF 6

出于调试目的,围绕该行:

myMediaElementExample.Play();
Run Code Online (Sandbox Code Playgroud)

try{} catch{}块:

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

这将为您提供有关导致异常的更多信息.如果仍然不清楚用这个新信息更新问题.

如果myMediaElementExample是null那么我希望你得到一个System.NullReferenceException而不是你所看到的win32.您可以通过在线上设置断点myMediaElementExample.Play();并检查它来检查这一点.

一旦找到并修复了问题,就可以删除异常处理程序,或者如果要谨慎,请将其保留,但只能捕获MediaElement.Play引发的异常.