Reputation: 393
I am trying to make a seek bar for my mediaplayerelement which has an audio source. I tried to set my slider's max value to the total second of the audio source but it sets the zero. But if I do the same thing after a little time, slider's maximum value becomes the total time of the audio This is my code to set maximum value of the slider to duration of the audio file
if(file != null)
{
var MusicFile = MediaSource.CreateFromStorageFile(file);
Mp3Player.Source = MusicFile;
Mp3Player.MediaPlayer.Play();
MusicSlider.MaximumMp3Player.MediaPlayer.PlaybackSession.NaturalDuration.TotalSeconds;
PlayPauseIm.Source = new BitmapImage(new Uri("ms-appx:///Assets/Pause_Button.png"));
}
(Sorry for unaligment in the text I couldn't make it look right) I think if I make an event which runs when MediaPlayerElement Started to playing, it will work true but I don't know how to implement it.
Upvotes: 3
Views: 662
Reputation: 32785
I tried to set my slider's max value to the total second of the audio source but it sets the zero.
Actually, your approach is fine. However, the value of PlaybackSession.NaturalDuration.TotalSeconds
is not assigned Instantly. According to official document:
The natural duration of the media. The default value is a Duration structure that evaluates as Automatic, which is the value held if you query this property before
MediaOpened
.
For you requirement, you could get the value of PlaybackSession.NaturalDuration.TotalSeconds
after media opened to make sure it is value held.
Mp3Player.MediaPlayer.MediaOpened += MediaPlayer_MediaOpened;
private async void MediaPlayer_MediaOpened(Windows.Media.Playback.MediaPlayer sender, object args)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
MusicSlider.Maximum = Mp3Player.MediaPlayer.PlaybackSession.NaturalDuration.TotalSeconds;
});
}
The other way to get music duration is to read file's MusicProperties
directly.
MusicProperties properties = await file.Properties.GetMusicPropertiesAsync();
TimeSpan myTrackDuration = properties.Duration;
MusicSlider.Maximum = myTrackDuration.TotalSeconds;
Both are available, you can choose one of them according to your design.
Upvotes: 1