How can I determine the length (i.e. duration) of a .wav file in C#?

后端 未结 15 2311
逝去的感伤
逝去的感伤 2020-11-30 00:26

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) *

15条回答
  •  Happy的楠姐
    2020-11-30 01:23

    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();
        }
      }
    }
    

提交回复
热议问题