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

后端 未结 15 2180
逝去的感伤
逝去的感伤 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;
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-30 01:29

    What exactly is your application doing with compressed WAVs? Compressed WAV files are always tricky - I always try and use an alternative container format in this case such as OGG or WMA files. The XNA libraries tend to be designed to work with specific formats - although it is possible that within XACT you'll find a more generic wav playback method. A possible alternative is to look into the SDL C# port, although I've only ever used it to play uncompressed WAVs - once opened you can query the number of samples to determine the length.

    0 讨论(0)
  • 2020-11-30 01:30

    In the .net framework there is a mediaplayer class:

    http://msdn.microsoft.com/en-us/library/system.windows.media.mediaplayer_members.aspx

    Here is an example:

    http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2667714&SiteID=1&pageid=0#2685871

    0 讨论(0)
提交回复
热议问题