Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting the duration of .wav file in resources

Tags:

c#

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?

like image 362
bRaNdOn Avatar asked Aug 15 '14 10:08

bRaNdOn


Video Answer


2 Answers

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.

like image 62
Benjamin Trent Avatar answered Oct 19 '22 22:10

Benjamin Trent


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;
like image 37
Leonhard P. Avatar answered Oct 19 '22 23:10

Leonhard P.