c语言读取wav音频文件输出浮点内容
时间: 2023-12-08 18:00:21 浏览: 116
好的,以下是一个简单的示例代码,可以实现读取wav音频文件并输出浮点内容:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef struct {
char ChunkID[4];
uint32_t ChunkSize;
char Format[4];
} RIFF_HEADER;
typedef struct {
char Subchunk1ID[4];
uint32_t Subchunk1Size;
uint16_t AudioFormat;
uint16_t NumChannels;
uint32_t SampleRate;
uint32_t ByteRate;
uint16_t BlockAlign;
uint16_t BitsPerSample;
} WAVE_FORMAT;
int main(int argc, char* argv[]) {
if (argc < 2) {
printf("Usage: %s <wav_file>\n", argv[0]);
return 1;
}
char* filename = argv[1];
FILE* fp = fopen(filename, "rb");
if (fp == NULL) {
printf("Cannot open file '%s'\n", filename);
return 2;
}
RIFF_HEADER riffheader;
fread(&riffheader, sizeof(riffheader), 1, fp);
if (strncmp(riffheader.ChunkID, "RIFF", 4) != 0 || strncmp(riffheader.Format, "WAVE", 4) != 0) {
printf("Invalid wav file!\n");
return 3;
}
WAVE_FORMAT wavefmt;
fread(&wavefmt, sizeof(wavefmt), 1, fp);
if (strncmp(wavefmt.Subchunk1ID, "fmt ", 4) != 0) {
printf("Invalid wav file!\n");
return 4;
}
uint32_t datasize = 0;
while (fread(&datasize, sizeof(datasize), 1, fp) > 0) {
if (strncmp((char*)&datasize, "data", 4) == 0) {
break;
}
fseek(fp, datasize, SEEK_CUR);
fread(&datasize, sizeof(datasize), 1, fp);
}
if (datasize == 0) {
printf("Invalid wav file!\n");
return 5;
}
uint32_t numsamples = datasize / (wavefmt.NumChannels * wavefmt.BitsPerSample / 8);
float* buffer = (float*)malloc(numsamples * sizeof(float));
for (uint32_t i = 0; i < numsamples; i++) {
int16_t sample[2];
fread(&sample, sizeof(sample), 1, fp);
buffer[i] = (float)sample[0] / INT16_MAX;
}
fclose(fp);
for (uint32_t i = 0; i < numsamples; i++) {
printf("%f\n", buffer[i]);
}
free(buffer);
return 0;
}
```
希望能够帮到你!
阅读全文