How can I detect whether a WAV file has a 44 or 46-byte header?

前端 未结 3 690
不知归路
不知归路 2020-12-03 03:21

I\'ve discovered it is dangerous to assume that all PCM wav audio files have 44 bytes of header data before the samples begin. Though this is common, many applications (ffmp

3条回答
  •  执笔经年
    2020-12-03 04:01

    The trick is to look at the "Subchunk1Size", which is a 4-byte integer beginning at byte 16 of the header. In a normal 44-byte wav, this integer will be 16 [10, 0, 0, 0]. If it's a 46-byte header, this integer will be 18 [12, 0, 0, 0] or maybe even higher if there is extra extensible meta data (rare?).

    The extra data itself (if present), begins in byte 36.

    So a simple C# program to detect the header length would look like this:

    static void Main(string[] args)
    {
        byte[] bytes = new byte[4];
        FileStream fileStream = new FileStream(args[0], FileMode.Open, FileAccess.Read);
        fileStream.Seek(16, 0);
        fileStream.Read(bytes, 0, 4);
        fileStream.Close();
        int Subchunk1Size = BitConverter.ToInt32(bytes, 0);
    
        if (Subchunk1Size < 16)
            Console.WriteLine("This is not a valid wav file");
        else
            switch (Subchunk1Size)
            {
                case 16:
                    Console.WriteLine("44-byte header");
                    break;
                case 18:
                    Console.WriteLine("46-byte header");
                    break;
                default:
                    Console.WriteLine("Header contains extra data and is larger than 46 bytes");
                    break;
            }
    }
    

提交回复
热议问题