gpt4 book ai didi

c++ - 在 C(或 C++)中循环遍历 WAV 文件

转载 作者:搜寻专家 更新时间:2023-10-31 02:11:19 24 4
gpt4 key购买 nike

我正在尝试用 C 语言复制 WAV 声音。原始文件是一个 2 秒的文件,但我想多次复制目标文件中的数据,以便播放时间更长。例如,如果我复制它 3 次,它应该播放 6 秒……对吗?

但由于某些原因,即使目标文件比原始文件大,它仍然播放了 2 秒......有人可以帮忙吗?

这是我的代码:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>

using namespace std;

typedef struct header_file
{
char chunk_id[4];
int chunk_size;
char format[4];
char subchunk1_id[4];
int subchunk1_size;
short int audio_format;
short int num_channels;
int sample_rate;
int byte_rate;
short int block_align;
short int bits_per_sample;
char subchunk2_id[4];
int subchunk2_size;
} header;

typedef struct header_file* header_p;




int main()

{
FILE * infile = fopen("../files/man1_nb.wav","rb"); // Open wave file in read mode
FILE * outfile = fopen("../files/Output.wav","wb"); // Create output ( wave format) file in write mode

int BUFSIZE = 2; // BUFSIZE can be changed according to the frame size required (eg: 512)
int count = 0; // For counting number of frames in wave file.
short int buff16[BUFSIZE]; // short int used for 16 bit as input data format is 16 bit PCM audio
header_p meta = (header_p)malloc(sizeof(header)); // header_p points to a header struct that contains the wave file metadata fields
int nb; // variable storing number of byes returned
if (infile)
{
fread(meta, 1, sizeof(header), infile); // Read only the header
fwrite(meta,1, sizeof(*meta), outfile); // copy header to destination file
int looper = 0; // number of times sound data is copied
for(looper=0; looper <2; looper++){

while (!feof(infile))
{
nb = fread(buff16,1,BUFSIZE,infile); // Reading data in chunks of BUFSIZE
count++; // Incrementing Number of frames
fwrite(buff16,1,nb,outfile); // Writing read data into output file
}
fseek(infile, 44, SEEK_SET); // Go back to end of header
}
}
fclose(infile); fclose(outfile);
return 0;
}

最佳答案

你的读写代码部分都是错误的。

wav 文件有 RIFF format并由 tlv block 组成。每个 block 由 header 和数据组成。通常 wav 文件由 3 个 block 组成:带有 FOURCC 代码的格式 block 、带有 PCMWAVEFORMAT 结构的格式 block 和带有声音数据的数据 block 。此外,由于每个 block 的大小受 32 位长度保持字段的限制,因此通过将 wav 文件连接在一起来构建大文件。

您需要逐 block 解析文件,并逐 block 写入目标,相应地更新 header 。

关于c++ - 在 C(或 C++)中循环遍历 WAV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43778502/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com