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 s开发者_StackOverflowender, 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();
}
I found it, you just have to stop the audio first, then set the position:
TestAudio.Stop();
TestAudio.Position = TimeSpan.Zero;
The MediaElement has no built-in support for looping playback. You can use the MediaEnded event and simply set the media position to zero or you can call the Stop() method. Either one will put you at the beginning of your video/audio for playback.
public partial class MainPage : UserControl
{
public MainPage()
{
// Required to initialize variables
InitializeComponent();
// Used for loopback.
MyME.MediaEnded += new RoutedEventHandler(MyME_MediaEnded);
}
// MediaElement has no looping capabilities so need to set the position back
// to the begining after the video finishes in order to play again.
// Or you can use the stop method
void MyME_MediaEnded(object sender, RoutedEventArgs e)
{
//MyME.Position = TimeSpan.Zero;
MyME.Stop();
}
private void BtnPlay_Click(object sender, RoutedEventArgs e)
{
MyME.Play();
}
private void BtnPause_Click(object sender, RoutedEventArgs e)
{
MyME.Pause();
}
private void BtnStop_Click(object sender, RoutedEventArgs e)
{
MyME.Stop();
}
}
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();
};
}
精彩评论