I’m using the following code to play sound on a button click.
public class AudioHelper
{
public async static void playButtonClick()
{
MediaElement snd = new MediaElement();
StorageFolder folder = await Package.Current.InstalledLocation.GetFolderAsync("Audios");
StorageFile file = await folder.GetFileAsync("buttonClick.m4a");
var stream = await file.OpenAsync(FileAccessMode.Read);
snd.SetSource(stream, file.ContentType);
snd.Play();
}
}
I called the code from the button click event using the following codes:
private void btnFlashCard_Click(object sender, RoutedEventArgs e)
{
AudioHelper.playButtonClick();
this.Frame.Navigate(typeof(LevelSelection));
}
since the playButtonClick is async, the page navigate to the LevelSelection page before the audio start playing. How do I make it so that the audio play first then the page navigate? Thank you.
EDIT:
Thanks to @htcdmrl I was able to figure out how to do this. As I mentioned in the comment, in order for the MediaEnded event to fire, the MediaElement has to be in the visual tree. I added the following code in the xaml and modify the code slightly to get it to work.
I added the following code to XAML:
<Frame HorizontalAlignment="Left" Margin="10,742,0,0" VerticalAlignment="Top">
<MediaElement x:Name="me" HorizontalAlignment="Left" Height="100" Margin="20,742,0,-74" VerticalAlignment="Top" Width="100" RenderTransformOrigin="0.359,-0.219"/>
</Frame>
Added the following codes to MainPage.Xaml.cs
public MainPage()
{
this.InitializeComponent();
me.MediaEnded += me_MediaEnded;
}
void me_MediaEnded(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(typeof(LevelSelection));
}
and change playButtonclick and btnFlashCard_Click to the following:
private void btnFlashCard_Click(object sender, RoutedEventArgs e)
{
playButtonClick();
}
public async void playButtonClick()
{
StorageFolder folder = await Package.Current.InstalledLocation.GetFolderAsync("Audios");
StorageFile file = await folder.GetFileAsync("buttonClick.m4a");
var stream = await file.OpenAsync(FileAccessMode.Read);
me.SetSource(stream, file.ContentType);
me.Play();
}
Add media ended event to your media element;
Then add your event;