2009-12-01 102 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" />