linux c语言读取wav文件的文件头
时间: 2023-11-25 20:07:23 浏览: 99
c语言读取wav格式文件头
以下是读取wav文件头的C代码示例:
```c
#include <stdio.h>
#include <stdint.h>
typedef struct {
char chunk_id[4];
uint32_t chunk_size;
char format[4];
} riff_header_t;
typedef struct {
char subchunk1_id[4];
uint32_t subchunk1_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;
} fmt_chunk_t;
typedef struct {
char subchunk2_id[4];
uint32_t subchunk2_size;
} data_chunk_t;
int main(int argc, char** argv)
{
if (argc < 2) {
printf("Usage: %s <wav_file>\n", argv[0]);
return 1;
}
FILE* fp = fopen(argv[1], "rb");
if (!fp) {
printf("Failed to open file %s\n", argv[1]);
return 1;
}
// Read RIFF header
riff_header_t riff_header;
fread(&riff_header, sizeof(riff_header), 1, fp);
// Make sure it's a WAV file
if (strncmp(riff_header.chunk_id, "RIFF", 4) ||
strncmp(riff_header.format, "WAVE", 4)) {
printf("%s is not a WAV file\n", argv[1]);
fclose(fp);
return 1;
}
// Read fmt chunk
fmt_chunk_t fmt_chunk;
fread(&fmt_chunk, sizeof(fmt_chunk), 1, fp);
// Make sure it's a PCM file
if (fmt_chunk.audio_format != 1) {
printf("%s is not a PCM file\n", argv[1]);
fclose(fp);
return 1;
}
// Read data chunk
data_chunk_t data_chunk;
fread(&data_chunk, sizeof(data_chunk), 1, fp);
// Print information
printf("Channels: %d\n", fmt_chunk.num_channels);
printf("Sample rate: %d\n", fmt_chunk.sample_rate);
printf("Bits per sample: %d\n", fmt_chunk.bits_per_sample);
printf("Data size: %d\n", data_chunk.subchunk2_size);
fclose(fp);
return 0;
}
```
这个示例读取了一个WAV文件的文件头,并打印了一些信息,如通道数、采样率、每个样本的位数和数据大小。请注意,此代码仅适用于标准的PCM WAV文件。如果您要处理其他类型的WAV文件,请根据需要修改代码。
阅读全文