views:

247

answers:

2

I have a variable MediaElement variable named TestAudio in my Silverlight app.

When I click the button, it plays the audio correctly.

But when I click the button again, it does not play the audio.

How can I make the MediaElement play a second time?

None of the tries below to put position back to 0 worked:

private void Button_Click_PlayTest(object sender, RoutedEventArgs e)
{
    //TestAudio.Position = new TimeSpan(0, 0, 0);
    //TestAudio.Position = TestAudio.Position.Add(new TimeSpan(0, 0, 0));
    //TestAudio.Position = new TimeSpan(0, 0, 0, 0, 0);
    //TestAudio.Position = TimeSpan.Zero;

    TestAudio.Play();
}
+2  A: 

I found it, you just have to stop the audio first, then set the position:

TestAudio.Stop();
TestAudio.Position = TimeSpan.Zero;
Edward Tanguay
A: 

I found the above did not work for me, and the only way I could get it working was to create a mediaelement dynamically. Heres the code I used - I copied the values from a MediaElement named mePlayClick I initially put in the XAML but you may not need to do this.

    private void Play_MediaSound()
    {
        // Create new media element dynamically
        MediaElement mediaElement = new MediaElement();

        // Reuse settings in XAML 
        mediaElement.Volume = mePlayClick.Volume;
        mediaElement.Source = mePlayClick.Source;
        mediaElement.AutoPlay = mePlayClick.AutoPlay;

        // WHen the media ends, remove the media element
        mediaElement.MediaEnded += (sender, args) =>
        {
            LayoutRoot.Children.Remove(mediaElement);
            mediaElement = null;
        };

        // Add the media element, must be in visual ui tree
        LayoutRoot.Children.Add(mediaElement);

        // When opened, play
        mediaElement.MediaOpened += (sender, args) =>
        {
            mediaElement.Play();
        };
    }
eagle779