欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

将16bit单声道WAV格式文件转为8bit PCM格式文件

程序员文章站 2022-07-01 22:22:12
...

1.扩展知识

wav文件格式分析与详解

PCM文件格式简单介绍

wav音频文件头解析

WAV文件头读取

 

2.代码(convert_sample_rate.c)

#include <stdio.h>
#include <string.h>
#include <errno.h>

int main(int argc, char **argv)
{
        FILE *from = NULL;
        FILE *to = NULL;
        int i, n, ret = 0;
        char path[256 + 1];
        char *src;
        char buf[4];
        char head_buff[44] = {0};

        printf("Convert sample rate 16000 -> 8000\n");

        if (argc == 1)
        {
                ret = -1;
                goto show_usage;
        }

        for (i = 1; i < argc; i++)
        {
                src = argv[i];
                snprintf(path, sizeof(path), "%s.pcm", src);
                from = fopen(src, "r");
                if (NULL == from)
                {
                        printf("error: open [%s] failed, %s\n", src, strerror(errno));
                        ret = -1;
                        goto next_file;
                }
                to = fopen(path, "w+");
                if (NULL == to)
                {
                        printf("error: open [%s] failed, %s\n", path, strerror(errno));
                        ret = -1;
                        goto next_file;
                }

                //去掉44字节文件头
                if(fread(head_buff, 1, 44, from) != 44)
                {
                    printf("Read Wav Head Error!\n");
                }

                printf("%2d: %60s -> %60s\n", i, src, path);
                while ((n = fread(buf, 1, 4, from)) == 4)
                {
                        if (2 != fwrite(buf, 1, 2, to))
                        {
                                printf("error: write failed\n");
                                break;
                        }
                }
next_file:
                if (NULL != from)
                        fclose(from);
                if (NULL != to)
                        fclose(to);
        }

        if (0 == ret)
                return 0;

show_usage:
        printf("Usage: %s [file_1] [file_n] [...] [file_n]\n", argv[0]);

        return 0;
}