C语言使用fopen_s将wav文件转换为txt格式
时间: 2024-05-03 21:19:59 浏览: 110
以下是将wav文件转换为txt格式的C语言代码示例:
```c
#include <stdio.h>
int main()
{
FILE *fp_in, *fp_out;
char input_file[100], output_file[100], buffer[4];
int data_size, sample_rate, num_channels, byte_rate, bits_per_sample, i, j, sample;
// 输入wav文件名
printf("Enter the input wav file name: ");
scanf("%s", input_file);
// 打开wav文件
if (fopen_s(&fp_in, input_file, "rb") != 0)
{
printf("Error opening input file.\n");
return 1;
}
// 读取wav文件头信息
fseek(fp_in, 22, SEEK_SET);
fread(&num_channels, sizeof(short), 1, fp_in);
fseek(fp_in, 24, SEEK_SET);
fread(&sample_rate, sizeof(int), 1, fp_in);
fseek(fp_in, 34, SEEK_SET);
fread(&bits_per_sample, sizeof(short), 1, fp_in);
fseek(fp_in, 40, SEEK_SET);
fread(&data_size, sizeof(int), 1, fp_in);
// 计算每个样本的字节数
byte_rate = num_channels * sample_rate * bits_per_sample / 8;
// 输入txt文件名
printf("Enter the output txt file name: ");
scanf("%s", output_file);
// 打开txt文件
if (fopen_s(&fp_out, output_file, "w") != 0)
{
printf("Error opening output file.\n");
return 1;
}
// 读取每个样本并写入txt文件
for (i = 0; i < data_size / byte_rate; i++)
{
for (j = 0; j < num_channels; j++)
{
fread(buffer, sizeof(char), bits_per_sample / 8, fp_in);
sample = 0;
for (int k = 0; k < bits_per_sample / 8; k++)
{
sample |= buffer[k] << (k * 8);
}
fprintf(fp_out, "%d ", sample);
}
fprintf(fp_out, "\n");
}
// 关闭文件
fclose(fp_in);
fclose(fp_out);
printf("Wav file converted to txt successfully.\n");
return 0;
}
```
运行此程序后,用户将被要求输入输入wav文件名和输出txt文件名。程序将打开输入文件并读取其头信息,然后计算每个样本的字节数。接下来,程序将打开输出文件并读取每个样本,并将其写入输出文件。最后,程序将关闭文件并打印成功消息。
阅读全文