Home > OS >  How to get the duration of MediaPlayer(.wav) music object? c#
How to get the duration of MediaPlayer(.wav) music object? c#

Time:03-25

Is there any way to get the duration of wav file (System.Windows.Media) in C# .Net framework? I just need to get state if the MediaPlayer music object ended.

I tried looking for the solution, but except already knowing the duration of music i did not find.

CodePudding user response:

Use the NaturalDuration property of the MediaPlayer. It will only populate after the file has been opened.

https://docs.microsoft.com/en-us/dotnet/api/system.windows.media.mediaplayer.naturalduration?view=windowsdesktop-6.0#system-windows-media-mediaplayer-naturalduration

So, probably something like this would work:

var mediaPlayer = new MediaPlayer();
mediaPlayer.Open(...);
var duration = mediaPlayer.Duration;

Media player also provides events you can wire up to for more information about the file loading correctly, etc.

Also be aware that the MediaPlayer is probably not the right choice if you're working with a lot of media files. You'll want to find a 3rd party library on NuGet or someplace with more better support.

  • Related