MediaElement不播放声音(最小可行示例)

时间:2015-09-21 13:37:40

标签: c# wpf windows xaml audio

我正在开发Windows App(Windows 8.1)。在我的xaml我有一个MediaElement链接到.wav文件夹中的/Assets文件。我点击按钮时想播放声音,但我无法实现。这是再现该问题的最小可行示例。你能救我吗?

这是XAML文件:

<Page
    x:Class="TrySoundsDesktop.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:TrySoundsDesktop"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <StackPanel Orientation="Vertical">
        <TextBlock FontSize="50" HorizontalAlignment="Center">
            TRY PLAY SOUND
        </TextBlock>
        <MediaElement x:Name="clickSound"                      
                      Loaded="clickSound_Loaded"
                      MediaFailed="clickSound_MediaFailed"
                      MediaOpened="clickSound_MediaOpened"
                      MediaEnded="clickSound_MediaEnded"
                      AudioCategory="ForegroundOnlyMedia"                      
                      Height="100" 
                      Width="100" 
                      Opacity="1"
                      Source="/Assets/applause.wav"
                      AutoPlay="False"
                      />
        <Button Click="Button_Click" Content="CLICK TO PLAY SOUND"/>
    </StackPanel>
</Page>

这就是背后的代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace TrySoundsDesktop
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();            
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {            
            clickSound.Play(); //The sound doesn't play
        }

        private void clickSound_MediaFailed(object sender, ExceptionRoutedEventArgs e)
        {
            //Not fired
        }

        private void clickSound_MediaOpened(object sender, RoutedEventArgs e)
        {
            //Not fired
        }

        private void clickSound_MediaEnded(object sender, RoutedEventArgs e)
        {
            //Not fired
        }

        private void clickSound_Loaded(object sender, RoutedEventArgs e)
        {
            //THIS METHOD FIRES
        }
    }
}

正如您所看到的,这是一个非常基本的例子。但它不起作用。提前谢谢。

0 个答案:

没有答案