2

I am trying to get the length of a sound file using this code:

MediaElement mysound = new MediaElement();
mysound.Source = new Uri(@"D:\majed\Phone\PhoneProject\PhoneProject\Sound\ring1.wav",UriKind.RelativeOrAbsolute);
double length = mysound.NaturalDuration.TimeSpan.Seconds;

but I receive an exception that says "mysound.NaturalDuration.TimeSpan.Seconds is null"

What can I do?

Note : I do not want using ( play ) or ( open ) method .

Thank you all

Tim S. Van Haren
  • 8,861
  • 2
  • 30
  • 34
Majed
  • 21
  • 1
  • 2

2 Answers2

0

Yes indeed NaturalDuration will not be valid till Media is opened : http://msdn.microsoft.com/en-us/library/system.windows.controls.mediaelement.naturalduration.aspx
I see no way to do this otherwise.

basarat
  • 261,912
  • 58
  • 460
  • 511
0

According to MSDN,

NaturalDuration is not accurate until the MediaOpened event has been raised.

MediaElement inherits from System.Windows.UIElement and is in the Systems.Windows.Controls namespace. By convention, it makes sense that a media player doesn't know certain media details of a file until the file is opened. If what you're after is just the length of a song file, perhaps you can check this out. Granted, it applies to MP3 files, but perhaps it can get you in the right direction.

bitxwise
  • 3,534
  • 2
  • 17
  • 22