音频—WAV格式及写入wav文件代码实现

1.RIFF规范

FIFF 是 Resource Interchange File Format(资源交换文件格式)的简称。RIFF 是一种文件格式规范,用于在计算机系统之间交换和存储多媒体资源。WAV 文件格式是 Microsoft 的 RIFF 规范的一个子集。

RIFF 规则定义了文件的结构和数据组织方式,包括文件头和数据块。它的结构如下:

RIFF 头部(12 字节):包含四个字节的文件标识符 "RIFF",四个字节的文件长度信息(不包括标识符和长度本身),以及四个字节的文件类型标识符。

数据块:紧随文件头的是一个或多个数据块,每个数据块包含一个四字节的标识符和四个字节的数据长度信息,以及实际的数据内容。

RIFF 还定义了很多不同的文件类型标识符(FourCC),用于标识特定类型的媒体资源,比如音频、视频、图像等。每种类型的文件都有特定的数据块结构和内容。

RIFF 文件格式的特点是灵活和可扩展,它允许在文件中包含不同类型的数据块,并且可以轻松添加新的数据块类型。这使得 RIFF 成为了多媒体资源交换和处理中常用的文件容器格式之一。

2.WAV文件格式

WAV 文件格式是 Microsoft 的 RIFF 规范的一个子集,用于存储多媒体文件。

wav 文件支持多种不同的比特率、采样率、多声道音频。

wav 文件由若干个 RIFF chunk 构成,分别为: RIFF WAVE Chunk,Format Chunk,Fact Chunk(可选),Data Chunk。另外,文件中还可能包含一些可选的区块,如:Fact chunk、Cue points chunk、Playlist chunk、Associated data list chunk 等。

具体格式如下:

文件解析说明:

wav 文件都是由 chunk 组成,chunk 的格式如下:

RIFF chunk:

typedef struct

{

    char ChunkID[4]; //'R','I','F','F'

    unsigned int ChunkSize;

    char Format[4];  //'W','A','V','E'

}riff_chunk;

其中 ChunkSize 代表的是整个 file_size 的大小减去 ChunkID 和 ChunkSize 的大小,即 file_size=ChunkSize+8。

fmt chunk:

typedef struct

{

    char FmtID[4];

    unsigned int FmtSize;

    unsigned short FmtTag;

    unsigned short FmtChannels;

    unsigned int SampleRate;

    unsigned int ByteRate;

    unsigned short BlockAilgn;

    unsigned short BitsPerSample;

}fmt_chunk;

data chunk:

struct DATA_CHUNK

{

    char DataID[4]; //'d','a','t','a'

    unsigned int DataSize;

};

3.wav文件示例分析

linux下 hd 工具查看原始数据:

4.16bit 声音数据格式

5.C代码实现wav文件写入保存

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

typedef struct

{

    char ChunkID[4]; //'R','I','F','F'

    unsigned int ChunkSize;

    char Format[4];  //'W','A','V','E'

}riff_chunk;

typedef struct

{

    char FmtID[4]; //'f','m','t'

    unsigned int FmtSize;

    unsigned short FmtTag;

    unsigned short FmtChannels;

    unsigned int SampleRate;

    unsigned int ByteRate;

    unsigned short BlockAilgn;

    unsigned short BitsPerSample;

}fmt_chunk;

typedef struct {

    char DataID[4]; //'d','a','t','a'

    unsigned int DataSize;

} data_chunk;

typedef struct {

    riff_chunk riff;

    fmt_chunk fmt;

    data_chunk data;

} wav_struct;

wav_struct gst_wav;

void init_wav()

{

    gst_wav.riff.ChunkID[0] = 'R';

    gst_wav.riff.ChunkID[1] = 'I';

    gst_wav.riff.ChunkID[2] = 'F';

    gst_wav.riff.ChunkID[3] = 'F';

    

    //计算回写数据长度

    gst_wav.riff.ChunkSize = 0;  //即 ChunkSize = file_size - 8

    gst_wav.riff.Format[0] = 'W';

    gst_wav.riff.Format[1] = 'A';

    gst_wav.riff.Format[2] = 'V';

    gst_wav.riff.Format[3] = 'E';

    gst_wav.fmt.FmtID[0] = 'f';

    gst_wav.fmt.FmtID[1] = 'm';

    gst_wav.fmt.FmtID[2] = 't';

    gst_wav.fmt.FmtID[3] = ' ';

    gst_wav.fmt.FmtSize = 16; //0x10=16 代表PCM编码方式

    gst_wav.fmt.FmtTag = 1; //为1,代表PCM编码方式

    

    //双通道

    gst_wav.fmt.FmtChannels = 2; //通道个数

    gst_wav.fmt.SampleRate = 48077;  //采样频率 48.077KHz

    gst_wav.fmt.ByteRate = 192308; //传输速率,每秒的字节数,计算公式为:SampleRate * FmtChannels * BitsPerSample/8

    gst_wav.fmt.BlockAilgn = 4; //16*2/8

    gst_wav.fmt.BitsPerSample = 16; //采样位数,一般有8/16/24/32/64

    gst_wav.data.DataID[0] = 'd';

    gst_wav.data.DataID[1] = 'a';

    gst_wav.data.DataID[2] = 't';

    gst_wav.data.DataID[3] = 'a';

    

    //计算回写数据长度

    gst_wav.data.DataSize = 0;  //即 DataSize = file_size - 44

}

int main(int argc, char *argv[])

{

    FILE *file;

    char *text = "1237894561238878";  //实际应用中为采集的音频数据

    size_t text_len = strlen(text);

    file = fopen("test.wav", "wb+");

    if (file == NULL) {

        perror("Error opening file");

        return EXIT_FAILURE;

    }

    //写入文件头

    init_wav();

    fwrite(&gst_wav, sizeof(char), sizeof(gst_wav), file);

    //写入音频数据

    fwrite(text, sizeof(char), text_len, file);

    //回写音频文件长度

    int fileSize = ftell(file);

    fseek(file, 4, SEEK_SET);  //回写

    fileSize = fileSize - 8;

    fwrite(&fileSize, sizeof(char), sizeof(fileSize), file);

    fseek(file, 40, SEEK_SET); //回写

    fileSize = fileSize + 8 - 44;

    fwrite(&fileSize, sizeof(char), sizeof(fileSize), file);

    fclose(file);

}

以下是使用FFmpeg将音频解码为WAV格式的示例代码: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <inttypes.h> #include <math.h> #include <libavutil/channel_layout.h> #include <libavutil/common.h> #include <libavutil/frame.h> #include <libavutil/opt.h> #include <libavutil/samplefmt.h> #include <libavutil/timestamp.h> #include <libavcodec/avcodec.h> #include <libavformat/avformat.h> #include <libswresample/swresample.h> #define AUDIO_INBUF_SIZE 20480 #define AUDIO_REFILL_THRESH 4096 static void decode(AVCodecContext *dec_ctx, AVPacket *pkt, AVFrame *frame, FILE *outfile) { int i, ch; int ret, data_size; /* send the packet with the compressed data to the decoder */ ret = avcodec_send_packet(dec_ctx, pkt); if (ret < 0) { fprintf(stderr, "Error submitting the packet to the decoder\n"); exit(1); } /* read all the output frames (in general there may be any number of them) */ while (ret >= 0) { ret = avcodec_receive_frame(dec_ctx, frame); if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) return; else if (ret < 0) { fprintf(stderr, "Error during decoding\n"); exit(1); } data_size = av_get_bytes_per_sample(dec_ctx->sample_fmt); if (data_size < 0) { /* This should not occur, checking just for paranoia */ fprintf(stderr, "Failed to calculate data size\n"); exit(1); } for (i = 0; i < frame->nb_samples; i++) for (ch = 0; ch < dec_ctx->channels; ch++) fwrite(frame->data[ch] + data_size*i, 1, data_size, outfile); } } int main(int argc, char **argv) { AVCodec *codec; AVCodecContext *codec_ctx = NULL; AVCodecParserContext *parser = NULL; AVFormatContext *fmt_ctx = NULL; AVPacket *pkt = NULL; AVFrame *frame = NULL; uint8_t inbuf[AUDIO_INBUF_SIZE + AV_INPUT_BUFFER_PADDING_SIZE]; int inbuf_size; int64_t pts; int ret; int i; if (argc <= 1) { fprintf(stderr, "Usage: %s <input file>\n", argv[0]); exit(0); } /* register all the codecs */ av_register_all(); /* allocate the input buffer */ pkt = av_packet_alloc(); if (!pkt) { fprintf(stderr, "Failed to allocate packet\n"); exit(1); } /* open the input file */ ret = avformat_open_input(&fmt_ctx, argv[1], NULL, NULL); if (ret < 0) { fprintf(stderr, "Cannot open input file '%s'\n", argv[1]); exit(1); } /* retrieve stream information */ ret = avformat_find_stream_info(fmt_ctx, NULL); if (ret < 0) { fprintf(stderr, "Cannot find stream information\n"); exit(1); } /* select the audio stream */ ret = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_AUDIO, -1, -1, &codec, 0); if (ret < 0) { fprintf(stderr, "Cannot find an audio stream in the input file\n"); exit(1); } int audio_stream_idx = ret; /* allocate the codec context */ codec_ctx = avcodec_alloc_context3(codec); if (!codec_ctx) { fprintf(stderr, "Failed to allocate codec context\n"); exit(1); } /* fill the codec context based on the stream information */ ret = avcodec_parameters_to_context(codec_ctx, fmt_ctx->streams[audio_stream_idx]->codecpar); if (ret < 0) { fprintf(stderr, "Failed to copy codec parameters to codec context\n"); exit(1); } /* init the codec context */ ret = avcodec_open2(codec_ctx, codec, NULL); if (ret < 0) { fprintf(stderr, "Failed to open codec\n"); exit(1); } /* allocate the frame */ frame = av_frame_alloc(); if (!frame) { fprintf(stderr, "Failed to allocate frame\n"); exit(1); } /* init the packet parser */ parser = av_parser_init(codec_ctx->codec_id); if (!parser) { fprintf(stderr, "Failed to init packet parser\n"); exit(1); } /* open the output file */ FILE *outfile = fopen("output.wav", "wb"); if (!outfile) { fprintf(stderr, "Failed to open output file\n"); exit(1); } /* read packets from the input file */ while (1) { /* get more data from the input file */ ret = av_read_frame(fmt_ctx, pkt); if (ret < 0) break; /* if this is not the audio stream, ignore it */ if (pkt->stream_index != audio_stream_idx) { av_packet_unref(pkt); continue; } /* send the packet to the parser */ inbuf_size = pkt->size; memcpy(inbuf, pkt->data, inbuf_size); while (inbuf_size > 0) { ret = av_parser_parse2(parser, codec_ctx, &pkt->data, &pkt->size, inbuf, inbuf_size, AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0); if (ret < 0) { fprintf(stderr, "Error while parsing\n"); exit(1); } inbuf += ret; inbuf_size -= ret; /* if we have a complete frame, decode it */ if (pkt->size > 0) { decode(codec_ctx, pkt, frame, outfile); } } av_packet_unref(pkt); } /* flush the decoder */ decode(codec_ctx, NULL, frame, outfile); /* close the output file */ fclose(outfile); /* free the resources */ av_parser_close(parser); avcodec_free_context(&codec_ctx); av_frame_free(&frame); av_packet_free(&pkt); avformat_close_input(&fmt_ctx); return 0; } ``` 这个程序使用FFmpeg库将音频文件解码为WAV格式,并将解码后的数据写入到一个输出文件中。你可以将输入文件的路径作为程序的参数来运行它。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI+程序员在路上

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值