开发者

Extracting duration using System.Window.Media.MediaPlayer sometimes doesn't work

I use the System.Window.Media.MediaPlayer Object to extract the duration of vari开发者_如何学Cous local soundfiles in my windows application.

TimeSpan duration = new TimeSpan(0);
MediaPlayer player = new MediaPlayer();

player.Open(new Uri(filename));

if (player.NaturalDuration.HasTimeSpan)
{
    duration = player.NaturalDuration.TimeSpan;
}

player.Close();

But the problem is that sometimes (even with same files and at different code place) the duration is "0".

Has anyone an idea?

Thx 4 answers


first check if file was loaded. simply monitor for an OpenStateChanged event. Then call something like

duration = player.CurrentMedia.Duration;

or for a string result:

duration = player.CurrentMedia.DurationString;


I suppose you finally found the solution to your problem. Anyway I leave an answer for those arriving here.

From the documentation:

Remarks: NaturalDuration cannot be determined until after MediaOpened has occurred.

So you have to wait until media is actually opened:

player.MediaOpened += new EventHandler(player_MediaOpened);

...

private void player_MediaOpened(Object sender, EventArgs e)
{
    if (player.NaturalDuration.HasTimeSpan)
    {
        duration = player.NaturalDuration.TimeSpan;
    }
    else
    {
        // Duration is Automatic
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜