获取wave文件的C函数代码
时间: 2023-12-08 08:03:53 浏览: 55
以下是一个获取wave文件的C函数的简单示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.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;
} WAV_HEADER;
int read_wave_file(char* filename, short** data, int* num_samples) {
FILE* fp = fopen(filename, "rb");
if (fp == NULL) {
printf("Error: failed to open file %s\n", filename);
return -1;
}
WAV_HEADER header;
fread(&header, sizeof(header), 1, fp);
if (memcmp(header.ChunkID, "RIFF", 4) != 0 ||
memcmp(header.Format, "WAVE", 4) != 0 ||
memcmp(header.Subchunk1ID, "fmt ", 4) != 0 ||
memcmp(header.Subchunk2ID, "data", 4) != 0) {
printf("Error: invalid wave file format\n");
fclose(fp);
return -1;
}
*num_samples = header.Subchunk2Size / sizeof(short);
*data = (short*)malloc(header.Subchunk2Size);
fread(*data, header.Subchunk2Size, 1, fp);
fclose(fp);
return 0;
}
int main() {
short* data;
int num_samples;
int ret = read_wave_file("test.wav", &data, &num_samples);
if (ret == 0) {
printf("Number of samples: %d\n", num_samples);
// Do something with the audio data...
free(data);
}
return 0;
}
```
该函数首先打开指定的wave文件,并按照wave文件格式读取音频数据。它将音频数据存储在一个short类型的数组中,并返回音频数据的总样本数。函数返回0表示读取成功,返回-1表示读取失败。
阅读全文