void* ReadFile(const char* path, unsigned int* len)
{
FILE* fp = fopen(path, "rb");
if (fp == NULL)
return NULL;
fseek(fp, 0, SEEK_END);
*len = ftell(fp);
fseek(fp, 0, SEEK_SET);
void* buffer = malloc(*len);
*len = fread(buffer, 1, *len, fp);
fclose(fp);
return buffer;
}
void* PcmToWav(const void* pcm, unsigned int pcmlen, unsigned int* wavlen)
{
//44字节wav头
void* wavHead = malloc(pcmlen + kSizeOfFormat44);
*wavlen = pcmlen + 44;
memcpy_s(wavHead, 4, "RIFF", 4); // [4] 'RIFF'
*(int*)((char*)wavHead + 4) = pcmlen + 36; // [4] 文件长度-8
memcpy_s(((char*)wavHead + 8), 8, "WAVEfmt ", 8); // [4] 'WAVEfmt '
*(int*)((char*)wavHead + 16) = 16; // [4] =0x10,下个结构体大小(16B)
*(short*)((char*)wavHead + 20) = 1; // [2] =0x01
*(short*)((char*)wavHead + 22) = 1; // [2] 通道数,为1或2
*(int*)((char*)wavHead + 24) = k16SamplesPerSec; // [4] 采样率,如16k(16000)
*(int*)((char*)wavHead + 28) = k16SamplesPerSec * kBitsPerSample / 8 * kSoundChannelNum; // [4] 每秒播放字节数,为 采样率*(量化数/8)*声道数
*(short*)((char*)wavHead + 32) = 1; // [2] 采样一次占字节数,为 声道数*(量化数/8)
*(short*)((char*)wavHead + 34) = kBitsPerSample; // [2] 量化数,如16bit
strcpy((char*)(char*)wavHead + 36, "data"); // [4] data id,如'data' or 'fact'
*(int*)((char*)wavHead + 40) = pcmlen;
memcpy_s(((char*)wavHead + 44), pcmlen, pcm, pcmlen);
return wavHead;// [4] 采样数据字节数
}
int PcmFileToWavFile(const char* pcmFilePath, const char* srcFilePath)
{
int ret = -1;
unsigned int pcmlen;
void *pcm = NULL;
void* wav = NULL;
pcm = ReadFile(pcmFilePath, &pcmlen); //读取pcm文件
if (pcm == NULL) {
LOG(ERROR) << "【PcmFileToWavFile】ReadFile failed,pcmFilePath:" << pcmFilePath << ",GetLastError:" << GetLastError();
ret = 1;
goto END;
}
unsigned int wavLen;
wav = PcmToWav(pcm, pcmlen, &wavLen); //加wav头
if (srcFilePath == NULL)
{
LOG(ERROR) << "【PcmFileToWavFile】 srcFilePath is not exist,srcFilePath:" << srcFilePath << ",GetLastError:" << GetLastError();
ret = 1;
goto END;
}
FILE* fwav = fopen(srcFilePath, "wb");
fwrite(wav, 1, wavLen, fwav);
ret = 0;
END:
if (pcm != NULL)
{
free(pcm);
}
if (wav != NULL)
{
free(wav);
fclose(fwav);
}
return ret;
}
pcm转wav
于 2023-01-16 11:05:00 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)