简体   繁体   中英

Get Sound File Length in c#

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM