簡體   English   中英

如何在WPF中播放聲音

[英]How to play a sound in WPF

我是C#的新手,使用VS 2008無法在WPF(Windows)應用程序中播放音樂。這是一個Web應用程序。 我認為正在發生的是myMediaElementExample變量在用於執行ExpenseReportPage.xaml.cs文件中的Play方法時為空。

現在,此程序已生成,但運行后,在myMediaElementExample.Play();處遇到異常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);
            }
    }
}

出於調試目的,請圍繞以下行:

myMediaElementExample.Play();

使用try{} catch{}塊:

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

這將為您提供有關導致異常的原因的更多信息。 如果仍然不清楚,請使用此新信息更新問題。

如果myMediaElementExample為null,那么我希望您得到一個System.NullReferenceException而不是您看到的win32。 您可以通過在myMediaElementExample.Play();上設置一個斷點來進行檢查myMediaElementExample.Play(); 線並檢查它。

找到並解決問題后,您可以刪除異常處理程序,或者如果要謹慎保留,則僅捕獲MediaElement.Play引發的異常。

謝謝克里斯和諾拉。 我確實找到了異常原因:

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

但是我發現了一個非常簡單的解決方法! 我用谷歌搜索解決方案:

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

在xaml文件中。

您最初的問題的解決方案是將LoadedBehavior =“ Manual”添加到XAML中的MediaElement中。 例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM