C# 声音don';在windows phone中触摸按钮时无法播放。(按钮导航到下一页)

C# 声音don';在windows phone中触摸按钮时无法播放。(按钮导航到下一页),c#,.net,silverlight,xaml,windows-phone,C#,.net,Silverlight,Xaml,Windows Phone,我正在创建一个应用程序,它使用按钮导航到另一个页面,我想在用户触摸按钮时保持声音。当只有按钮时,代码工作正常,但当我使用按钮导航到另一个页面时,声音没有播放,而是在我按下Windows phone的“后退”按钮时播放 public void playSound() { MediaElement playSound1 = new MediaElement(); playSound1.Source = new Uri("/Sound/Lionsound.mp3", UriKind.R

我正在创建一个应用程序,它使用按钮导航到另一个页面,我想在用户触摸按钮时保持声音。当只有按钮时,代码工作正常,但当我使用按钮导航到另一个页面时,声音没有播放,而是在我按下Windows phone的“后退”按钮时播放

public void playSound()
{
    MediaElement playSound1 = new MediaElement();
    playSound1.Source = new Uri("/Sound/Lionsound.mp3", UriKind.Relative);
    playSound1.Play();
}

void btnClassicPuzzle_Click(object sender, System.Windows.RoutedEventArgs e)
{
    playSound();
    NavigationService.Navigate(new Uri("/Menu/SelectPack.xaml", UriKind.Relative));
}

您正在调用一个函数来播放按钮单击时的声音,并立即执行页面导航。编译器处理它的方式在
playSound1.Play()
之后,声音被启动,并立即调用
NavigationService
。页面被更改,当前页面中的所有对象都被销毁,因此声音停止。您需要做的是导航到
MediaEnded
事件的下一页,以便在导航前播放完整的声音

<MediaElement MediaEnded="eventhandler" ../>


您还可以使用
MediaPlayer.state
检查
MediaPlayer
状态;在导航之前

我认为您可以在应用程序中使用GlobalMediaElement

<MediaElement MediaEnded="eventhandler" ../>
要使用全局元素或全局MediaElement,可以按照以下步骤操作

首先在app.xaml中添加一个ControlTemplate

         <ControlTemplate x:Key="AudioContentTemplate">
        <Grid x:Name="MediaElementContainer">

          <!-- The media element used to play sound -->
          <MediaElement Loaded="OnGlobalMediaLoaded"
                        Visibility="Collapsed" />

          <!-- Added for the normal content -->
          <Grid x:Name="ClientArea">
            <ContentPresenter />
          </Grid>
        </Grid>
      </ControlTemplate>
app.xaml.cs末尾的第三个部分是初始化部分,在这里,您向系统中的全局Mediaelement注入了资源中的模板:

   private void Application_Launching(object sender, LaunchingEventArgs e)
   {


      RootFrame.Style = (Style)Resources["AudioContentTemplate"];

    }
最后,您可以在代码中调用它

  private void btnClassicPuzzle_Click(object sender, System.Windows.RoutedEventArgs e)
  {
    //play the globlal MediaElement 
     ((App)App.Current).playMedia(new Uri("/Sound/Lionsound.mp3", UriKind.Relative));

      NavigationService.Navigate(new Uri("/Menu/SelectPack.xaml", UriKind.Relative));
   }

当我删除这个部分时,NavigationService.Navigate(新Uri(“/Menu/SelectPack.xaml”,UriKind.Relative));声音很好听。