I'm currently looking for the solution of my problem since my audio file (.wav) is in the resources of my solution. I need to detect how long it would play.
How can I calculate the duration of the audio in my resources?
Is there a way to detect how long will it take to play a certain audio file in my resource?
You can use NAudio to read the resource stream and get the duration
using NAudio.Wave;
...
WaveFileReader reader = new WaveFileReader(MyProject.Resource.AudioResource);
TimeSpan span = reader.TotalTime;
You can also do what Matthew Watson suggested and simply keep the length as an additional string resource.
Also, this SO question has tons of different ways to determine duration but most of them are for files, not for streams grabbed from resources.
Ive got a way better solution for your problem, without any library. First read all bytes from the file. (optionally you can also use a FileSteam to only read the necessary bytes)
byte[] allBytes = File.ReadAllBytes(filePath);
After you got all bytes from your file, you need to get the bits per second. This value is usually stored in the bytes at indices 28-31.
int byterate = BitConverter.ToInt32(new[] { allBytes[28], allBytes[29], allBytes[30], allBytes[31] }, 0);
Now you can already get the duration in seconds.
int duration = (allBytes.Length - 8) / byterate;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With