1

我是一名新手 C# 程序员,在使用 VS 2008 在我的 WPF (Windows) 应用程序中播放音乐时遇到问题。这是一个网络应用程序。我认为正在发生的是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);
            }
    }
}
4

3 回答 3

6

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

myMediaElementExample.Play();

有一个try{} catch{}块:

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

这将为您提供有关导致异常的原因的更多信息。如果仍然不清楚,请使用此新信息更新问题。

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

一旦你发现并解决了问题,你可以删除异常处理程序,或者如果你想小心保留它,但只捕获MediaElement.Play引发的异常。

于 2009-12-01T22:39:02.273 回答
3

谢谢克里斯和诺拉。我确实找到了异常原因:

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

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

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

在 xaml 文件中。

于 2009-12-01T23:47:52.540 回答
0

原始问题的解决方案是将 LoadedBehavior="Manual" 添加到 XAML 中的 MediaElement。例如:

<MediaElement Source="Samples/robot.wmv" LoadedBehavior="Manual" />
于 2012-08-19T13:01:35.167 回答