iOS-PCM文件转WAV文件 发表于 2016-03-10 | 分类于 Objective-C | | PCM音频文件转WAV音频文件,在PCM数据的文件头加入一个44字节的字段。 WAV的格式为: 里面注意设置参数: 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667typedef struct{ char chChunkID[4]; int nChunkSize;}XCHUNKHEADER; //8typedef struct{ short nFormatTag; short nChannels; int nSamplesPerSec; int nAvgBytesPerSec; short nBlockAlign; short nBitsPerSample;}WAVEFORMATX; //16typedef struct{ char chRiffID[4]; int nRiffSize; char chRiffFormat[4];}RIFFHEADER; //12void WriteWAVEHeader(NSMutableData* fpwave, int pcmLength){ char tag[10] = ""; // 1. 写RIFF头 RIFFHEADER riff; strcpy(tag, "RIFF"); memcpy(riff.chRiffID, tag, 4); riff.nRiffSize = pcmLength + 44 - 8; //减去RIFF和nRiffSize 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 = 2; wfx.nSamplesPerSec = 44100; wfx.nBitsPerSample = 16; // 16位 wfx.nBlockAlign = wfx.nChannels * wfx.nBitsPerSample / 8; wfx.nAvgBytesPerSec = wfx.nBlockAlign * wfx.nSamplesPerSec; [fpwave appendBytes:&wfx length:sizeof(WAVEFORMATX)]; // 3. 写data块头 strcpy(tag, "data"); memcpy(chunk.chChunkID, tag, 4); chunk.nChunkSize = pcmLength; [fpwave appendBytes:&chunk length:sizeof(XCHUNKHEADER)];}+ (NSData*)pcmToWav:(NSData*)pcmData totalLength:(int)totalLength{ NSMutableData *wavData = [NSMutableData new]; WriteWAVEHeader(wavData, (int)totalLength); NSLog(@"%d", (int)wavData.length); [wavData appendData:pcmData]; return wavData;}