如何在WPF中播放声音

时间:2009-12-01 22:35:03

标签: c# .net wpf audio 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].

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

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();
        }
    }
}

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);
            }
    }
}

3 个答案:

答案 0 :(得分:6)

出于调试目的,请围绕以下行:

myMediaElementExample.Play();
带有try{} catch{}块的

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

这将为您提供有关导致异常的更多信息。如果还不清楚,请用这个新信息更新问题。

如果myMediaElementExample为空,那么我希望你得到System.NullReferenceException而不是你看到的win32。您可以通过在myMediaElementExample.Play();行上设置断点并进行检查来检查这一点。

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

答案 1 :(得分:3)

谢谢Chris和Norla。我确实找到了异常原因:

Cannot control media unless LoadedBehavior or UnloadedBehavior is set to Manual.

但是我找到了一个非常简单的解决方法!我用Google搜索了解决方案:

<MediaElement Source="The Boogie Monster.mp3" />

在xaml文件中。

答案 2 :(得分:0)

原始问题的解决方案是将LoadedBehavior =“Manual”添加到XAML中的MediaElement。 E.g:

<MediaElement Source="Samples/robot.wmv" LoadedBehavior="Manual" />
相关问题