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

后端 未结 15 2347
逝去的感伤
逝去的感伤 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:26

    You may consider using the mciSendString(...) function (error checking is omitted for clarity):

    using System;
    using System.Text;
    using System.Runtime.InteropServices;
    
    namespace Sound
    {
        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;
            }
        }
    }
    

提交回复
热议问题