c语言读取wav音频文件输出浮点内容
时间: 2023-12-08 20:01:07 浏览: 183
你可以通过以下步骤读取wav音频文件并输出浮点内容:
1. 打开wav文件并读取头信息
```
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char chunkID[4];
unsigned int chunkSize;
char format[4];
char subchunk1ID[4];
unsigned int subchunk1Size;
unsigned short audioFormat;
unsigned short numChannels;
unsigned int sampleRate;
unsigned int byteRate;
unsigned short blockAlign;
unsigned short bitsPerSample;
char subchunk2ID[4];
unsigned int subchunk2Size;
} WavHeader;
WavHeader readWavHeader(FILE *file) {
WavHeader header;
fread(&header, sizeof(header), 1, file);
return header;
}
int main() {
FILE *file = fopen("audio.wav", "rb");
if (!file) {
printf("Failed to open file\n");
return 1;
}
WavHeader header = readWavHeader(file);
printf("Sample rate: %d\n", header.sampleRate);
fclose(file);
return 0;
}
```
2. 读取音频数据并输出浮点内容
```
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct {
char chunkID[4];
unsigned int chunkSize;
char format[4];
char subchunk1ID[4];
unsigned int subchunk1Size;
unsigned short audioFormat;
unsigned short numChannels;
unsigned int sampleRate;
unsigned int byteRate;
unsigned short blockAlign;
unsigned short bitsPerSample;
char subchunk2ID[4];
unsigned int subchunk2Size;
} WavHeader;
WavHeader readWavHeader(FILE *file) {
WavHeader header;
fread(&header, sizeof(header), 1, file);
return header;
}
int16_t readInt16(FILE *file) {
int16_t value;
fread(&value, sizeof(value), 1, file);
return value;
}
float convertToFloat(int16_t value) {
const float multiplier = 1.0f / 32768.0f;
return value * multiplier;
}
int main() {
FILE *file = fopen("audio.wav", "rb");
if (!file) {
printf("Failed to open file\n");
return 1;
}
WavHeader header = readWavHeader(file);
printf("Sample rate: %d\n", header.sampleRate);
int numSamples = header.subchunk2Size / (header.numChannels * (header.bitsPerSample/8));
printf("Num samples: %d\n", numSamples);
for (int i = 0; i < numSamples; i++) {
int16_t sample = readInt16(file);
float value = convertToFloat(sample);
printf("%f\n", value);
}
fclose(file);
return 0;
}
```
这样就可以读取wav音频文件并输出浮点内容了。
阅读全文