2009-12-01 57 views
1

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

现在这个程序建立了,但是在我运行它之后,它在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); 
      } 
    } 
} 
+1

哇,我期待着一个简单的。 –

+0

你在哪里设置媒体源,即播放的mp3/wav? – kiwipom

回答

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引发的异常。

+0

用于防御性编程。为了获得额外的奖励,您可以设置一个记录器来向您发送例外详细信息。 –

3

谢谢克里斯和诺拉。我确实发现异常原因:

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

但是我发现一个非常简单的解决方法!我使用Google搜索解决方案:

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

in the xaml file。

0

解决您原来的问题是LoadedBehavior =“手册”在您的XAML添加到您的MediaElement。例如:

<MediaElement Source="Samples/robot.wmv" LoadedBehavior="Manual" />