There are two events that you'll find helpful.
- MediaStateChanged
(http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.media.mediaplayer.mediastatechanged.aspx) - ActiveSongChanged
(http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.media.mediaplayer.activesongchanged.aspx)
Register to these events and from the event handlers check MediaPlayer.Queue.ActiveSong.Duration
. The problem you're encountering is that the ActiveSong isn't set immediately after calling MediaPlayer.Play()
.
private void btnPlay_Click(object sender, EventArgs e)
{
using (MediaLibrary library = new MediaLibrary())
{
foreach (var item in library.Songs)
{
MediaPlayer.MediaStateChanged += _onMediaStateChanged; //register for event
MediaPlayer.ActiveSongChanged += _onActiveSongChanged;
FrameworkDispatcher.Update();
MediaPlayer.Play(item);
timer.Start();
// I just want to play the first song, so I break here
break;
}
library.Dispose();
}
}
private void _onMediaStateChanged(object sender, EventArgs e)
{
if(MediaPlayer.State == MediaState.Playing)
{
int duration = (int)MediaPlayer.Queue.ActiveSong.Duration.TotalMilliseconds;
processbar.Maximum = duration;
}
}
private void _onActiveSongChanged(object sender, EventArgs e)
{
int duration = (int)MediaPlayer.Queue.ActiveSong.Duration.TotalMilliseconds;
processbar.Maximum = duration;
}