12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- #include <stdio.h>
- #include <stdint.h>
-
- typedef struct {
- char chunkId[4];
- uint32_t chunkSize;
- char format[4];
- char fmt[4];
- uint32_t fmt_size;
- uint16_t audio_format;
- uint16_t num_channels;
- uint32_t sample_rate;
- uint32_t byte_rate;
- uint16_t block_align;
- uint16_t bits_per_sample;
- char data[4];
- uint32_t data_size;
- } WavHeader;
-
- int main(int argc, char *argv[]) {
- FILE *file;
- WavHeader header;
- uint32_t subchunk2Size;
- uint32_t byteRate;
- // uint32_t sampleRate;
- // uint32_t numChannels;
- // uint32_t bitsPerSample;
- uint32_t dataSize;
- double duration;
-
- if (argc < 2) {
- printf("Usage: %s <filename>\n", argv[0]);
- return 1;
- }
-
- file = fopen(argv[1], "rb");
- if (!file) {
- perror("Error opening file");
- return 1;
- }
-
- // 读取WAV文件头
- fread(&header, sizeof(WavHeader), 1, file);
-
- // 确保是RIFF WAVE CHUNK
- if (header.chunkId[0] != 'R' || header.chunkId[1] != 'I' || header.chunkId[2] != 'F' || header.chunkId[3] != 'F'
- || header.format[0] != 'W' || header.format[1] != 'A' || header.format[2] != 'V' || header.format[3] != 'E') {
- // printf("Not a valid WAV file.\n");
- printf("0");
- fclose(file);
- return 1;
- }
-
- // 跳过子块大小和格式信息
- // fseek(file, 12, SEEK_CUR);
-
- // 读取子块大小和字节率
- // fread(&subchunk2Size, sizeof(uint32_t), 1, file);
- // fread(&byteRate, sizeof(uint32_t), 1, file);
-
- // 读取样本率和通道数
- // fread(&sampleRate, sizeof(uint32_t), 1, file);
- // fread(&numChannels, sizeof(uint32_t), 1, file);
-
- // 读取样本位深度
- // fread(&bitsPerSample, sizeof(uint32_t), 1, file);
-
- // 计算数据大小
- // dataSize = subchunk2Size;
-
- // 计算时长(秒)
- duration = (double)header.chunkSize / (header.bits_per_sample * header.num_channels * header.sample_rate / 8);
-
- // printf("Channels: %hu \n", header.num_channels);
- // printf("Sample Rate: %u \n", header.sample_rate);
- // printf("Byte Rate: %hu \n", header.byte_rate);
- // printf("Bits per Sample: %hu \n", header.bits_per_sample);
- // printf("Data Size: %u \n", header.data_size);
- // printf("Duration %.2f seconds", duration);
- printf("%.2f", duration);
-
- fclose(file);
- return 0;
- }
|