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

后端 未结 15 2285
逝去的感伤
逝去的感伤 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条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 01:12

    i have tested blew code would fail,file formats are like "\\ip\dir\*.wav'

     public static class SoundInfo
       {
         [DllImport("winmm.dll")]
         private static extern uint mciSendString
         (
            string command,
            StringBuilder returnValue,
            int returnLength,
            IntPtr winHandle
         );
    
         public static int GetSoundLength(string fileName)
          {
            StringBuilder lengthBuf = new StringBuilder(32);
    
            mciSendString(string.Format("open \"{0}\" type waveaudio alias wave", fileName), null, 0, IntPtr.Zero);
            mciSendString("status wave length", lengthBuf, lengthBuf.Capacity, IntPtr.Zero);
            mciSendString("close wave", null, 0, IntPtr.Zero);
    
            int length = 0;
            int.TryParse(lengthBuf.ToString(), out length);
    
            return length;
        }
    }
    

    while naudio works

        public static int GetSoundLength(string fileName)
         {
            using (WaveFileReader wf = new WaveFileReader(fileName))
            {
                return (int)wf.TotalTime.TotalMilliseconds;
            }
         }`
    

提交回复
热议问题