Reputation: 5152
I'm using the MediaElement class to play a simple sound on a button click. That works fine for me unless I'm making a double tap on it. On the second tap I want the old sound to stop playing and restart the sound. But the Stop Method doesn't work:
public static MediaElement SoundDelete;
public static void PlaySoundCash()
{
if (SessionHelper.getConfig("SoundDelete") == "true")
{
System.Diagnostics.Debug.WriteLine(SoundDelete.Position.ToString());
SoundDelete.Stop(); //dosn't work
SoundDelete.Position = new System.TimeSpan(0,0,0,0,0); //dosn't work
System.Diagnostics.Debug.WriteLine(SoundDelete.Position.ToString());
SoundDelete.Play();
}
}
In the console the timespan is never 0. How can I get the sound playing from the beginning?
Upvotes: 0
Views: 1086
Reputation: 26
I was having the exact same issue. It turns out adding the MediaElement to the Visual Tree will allow you to use this extra functionality.
Adding my MediaElements to the children of my base Grid solved these issues.
For example:
C#
public static MediaElement SoundDelete;
private void MediaInit()
{
// ...
// load your sound file into SoundDelete
// ...
BaseGrid.Children.Add(SoundDelete);
}
public static void PlaySoundCash()
{
System.Diagnostics.Debug.WriteLine(SoundDelete.Position.ToString());
SoundDelete.Stop();
SoundDelete.Position = new System.TimeSpan.Zero;
System.Diagnostics.Debug.WriteLine(SoundDelete.Position.ToString());
SoundDelete.Play();
}
or in XAML:
<Grid Name="BaseGrid">
<MediaElement Name="SoundDelete" Source="path_to_your_sound_file.mp3" />
</Grid>
Upvotes: 1