给纯PCM数据添加WAV头文件的方法, 亲测可用。直接调用即可, 第一个参数传入要存放PCM数据的空指针, 第二个参数是PCM数据的长度, 直接[data length]; 简单来说就是: 先写wav头,后追加数据


typedef struct
{
char chChunkID[4];
int nChunkSize;
}XCHUNKHEADER; //8
typedef struct
{
short nFormatTag;
short nChannels;
int nSamplesPerSec;
int nAvgBytesPerSec;
short nBlockAlign;
short nBitsPerSample;
}WAVEFORMATX; //16
typedef struct
{
char chRiffID[4];
int nRiffSize;
char chRiffFormat[4];
}RIFFHEADER; //12
     
void WriteWAVEHeader(NSMutableData* fpwave, int nFrame)
{
char tag[10] = "";
     
// 1. 写RIFF头
RIFFHEADER riff;
strcpy(tag, "RIFF");
memcpy(riff.chRiffID, tag, 4);
    riff.nRiffSize = 4 + sizeof(XCHUNKHEADER) + sizeof(XCHUNKHEADER) + sizeof(WAVEFORMATX) + sizeof(XCHUNKHEADER) + nFrame - 8;
strcpy(tag, "WAVE");
memcpy(riff.chRiffFormat, tag, 4);
    [fpwave appendBytes:&riff length:sizeof(RIFFHEADER)];
     
// 2. 写FMT块
XCHUNKHEADER chunk;
WAVEFORMATX wfx;
strcpy(tag, "fmt ");
memcpy(chunk.chChunkID, tag, 4);
chunk.nChunkSize = sizeof(WAVEFORMATX);
    [fpwave appendBytes:&chunk length:sizeof(XCHUNKHEADER)];
memset(&wfx, 0, sizeof(WAVEFORMATX));
wfx.nFormatTag = 1;
wfx.nChannels = 1; // 单声道
wfx.nSamplesPerSec = 8000; // 8khz
wfx.nAvgBytesPerSec = 16000;
wfx.nBlockAlign = 2;
wfx.nBitsPerSample = 16; // 16位
    [fpwave appendBytes:&wfx length:sizeof(WAVEFORMATX)];
     
// 3. 写data块头
strcpy(tag, "data");
memcpy(chunk.chChunkID, tag, 4);
    chunk.nChunkSize = 4 + sizeof(XCHUNKHEADER) + sizeof(XCHUNKHEADER) + sizeof(WAVEFORMATX) + sizeof(XCHUNKHEADER) + nFrame - 44;
    [fpwave appendBytes:&chunk length:sizeof(XCHUNKHEADER)];
}