How can I determine the length (i.e. duration) of

2019-01-08 11:25发布

In the uncompressed situation I know I need to read the wav header, pull out the number of channels, bits, and sample rate and work it out from there: (channels) * (bits) * (samples/s) * (seconds) = (filesize)

Is there a simpler way - a free library, or something in the .net framework perhaps?

How would I do this if the .wav file is compressed (with the mpeg codec for example)?

15条回答
\"骚年 ilove
2楼-- · 2019-01-08 12:08

Download NAudio.dll from the link http://naudio.codeplex.com/

and then use this function

public static TimeSpan GetWavFileDuration(string fileName)       
{     
    WaveFileReader wf = new WaveFileReader(fileName);
    return wf.TotalTime; 
}

you will get the Duration

查看更多
Lonely孤独者°
3楼-- · 2019-01-08 12:08

I had difficulties with the example of the MediaPlayer-class above. It could take some time, before the player has opened the file. In the "real world" you have to register for the MediaOpened-event, after that has fired, the NaturalDuration is valid. In a console-app you just have to wait a few seconds after the open.

using System;
using System.Text;
using System.Windows.Media;
using System.Windows;

namespace ConsoleApplication2
{
  class Program
  {
    static void Main(string[] args)
    {
      if (args.Length == 0)
        return;
      Console.Write(args[0] + ": ");
      MediaPlayer player = new MediaPlayer();
      Uri path = new Uri(args[0]);
      player.Open(path);
      TimeSpan maxWaitTime = TimeSpan.FromSeconds(10);
      DateTime end = DateTime.Now + maxWaitTime;
      while (DateTime.Now < end)
      {
        System.Threading.Thread.Sleep(100);
        Duration duration = player.NaturalDuration;
        if (duration.HasTimeSpan)
        {
          Console.WriteLine(duration.TimeSpan.ToString());
          break;
        }
      }
      player.Close();
    }
  }
}
查看更多
聊天终结者
4楼-- · 2019-01-08 12:08

There's a bit of a tutorial (with - presumably - working code you can leverage) over at CodeProject.

The only thing you have to be a little careful of is that it's perfectly "normal" for a WAV file to be composed of multiple chunks - so you have to scoot over the entire file to ensure that all chunks are accounted for.

查看更多
Explosion°爆炸
5楼-- · 2019-01-08 12:14

Try code below from How to determine the length of a .wav file in C#

    string path = @"c:\test.wav";
    WaveReader wr = new WaveReader(File.OpenRead(path));
    int durationInMS = wr.GetDurationInMS();
    wr.Close();
查看更多
叼着烟拽天下
6楼-- · 2019-01-08 12:16

Download "PresentationCore.dll" and "WindowsBase.dll" from:

http://www.search-dll.com/dll-files/download/windowsbase.dll.html

Paste the files in you application bin folder for reference. It should work now.

查看更多
登录 后发表回答