当前位置: 首页 > 工具软件 > libsndfile > 使用案例 >

使用libsndfile写一个简单的wav转pcm工具

艾学海
2023-12-01
#include <stdlib.h>
#include <stdio.h>
#include <sndfile.h>
#include <memory.h>


#define RAW_BUFF_SIZE 1024

int main(int argv, const char *args[]) {
    if (argv!=2) {
        printf("please input wav file\n");
        exit(0);
    }

    SF_INFO info;
    SNDFILE *in = sf_open(args[1], SFM_READ, &info);
    if (!in) {
        fprintf(stderr, "cannot open file %s\n", args[1]);
        return 1;
    }

    char *p = strrchr(args[1], '.');
    int len = p-args[1];
    char *output_file = calloc(len+5, sizeof(char));
    strncpy(output_file, args[1], len);
    strcpy(output_file+len, ".pcm");

    SF_INFO onfo;
    onfo.channels = 1;
    onfo.samplerate = info.samplerate;
    onfo.format = SF_FORMAT_RAW | SF_FORMAT_PCM_16 ;
    onfo.sections = 0;
    onfo.seekable = 1;
    SNDFILE *out = sf_open(output_file, SFM_WRITE, &onfo);
    if (!out) {
        fprintf(stderr, "cannot open file %s\n", output_file);
        sf_close(in);
        return 2;
    }

    free(output_file);

    char buff[RAW_BUFF_SIZE];
    sf_count_t read = 0;
    do {
        read = sf_read_raw(in, buff, RAW_BUFF_SIZE);
        if (read >0) {
            sf_write_raw(out, buff, read);
        }
    } while (read >0);

    sf_close(in);
    sf_close(out);
}
 类似资料: