Playing sound on button click while moving to othe

2019-08-04 07:40发布

问题:

I'm using C# and I'm trying to make my button click which navigates me to a new page, to play a sound. The problem is that I can't hear the sound playing because the media element is in the previous page. Is there a way to play a sound but to hear it in all pages? Here is my code:

    private void Button_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
    {
        this.Frame.Navigate(typeof(Game));
        select.Play();
    }

select is my sound .wav and it plays if I don't have the navigation code....

回答1:

Playing a soundfile going from one form to the other like this should work fine. I placed my file in a Sounds folder inside the project

using Windows.ApplicationModel;
using Windows.Storage;

private async void ButtonPlay_Click(object sender, RoutedEventArgs e)
{
    MediaElement snd = new MediaElement();
    StorageFolder folder = await Package.Current.InstalledLocation.GetFolderAsync("Sounds");
    StorageFile file = await folder.GetFileAsync("Alarm01.wav");
    var stream = await file.OpenAsync(FileAccessMode.Read);
    snd.SetSource(stream, file.ContentType);
    snd.Play();
    this.Frame.Navigate(typeof(Game));

 }


回答2:

This way the problem that I had that the sound couldn't play the first time the app opens is fixed. :)

using Windows.ApplicationModel;
using Windows.Storage;



MediaElement snd = new MediaElement();

    private async void ButtonPlay_Click(object sender, RoutedEventArgs e)
{
    StorageFolder folder = await Package.Current.InstalledLocation.GetFolderAsync("Sounds");
    StorageFile file = await folder.GetFileAsync("Alarm01.wav");
    var stream = await file.OpenAsync(FileAccessMode.Read);
    snd.SetSource(stream, file.ContentType);
    this.Frame.Navigate(typeof(Game));
 }