用recordedTotalVoiceData 记录总的data数据(用于header的重写)
每次写frame之前 重写header即可
// 将pcm存为wav文件
-
(NSString *) getAndCreatePlayableFileFromPcmData:(BOOL)force :(NSData *)frame{
dispatch_async(self.ioQueue, ^{
short NumChannels = 1; //录音通道数 short BitsPerSample = 16; //线性采样位数 int SamplingRate = 16000; //录音采样率(Hz) int numOfSamples = (int)self.recordedTotalVoiceData.length; int ByteRate = NumChannels*BitsPerSample*SamplingRate/8; short BlockAlign = NumChannels*BitsPerSample/8; int DataSize = NumChannels*numOfSamples*BitsPerSample/8; int chunkSize = 16; int totalSize = 46 + DataSize; short audioFormat = 1; NSData *ttdata = [NSData dataWithContentsOfFile:self.wavFilePath]; const char *wavFilePathChar = [self.wavFilePath cStringUsingEncoding:NSUTF8StringEncoding]; @synchronized (self->_recordedTotalVoiceData) { FILE *fout = fopen(wavFilePathChar, "r+"); if (ttdata.length == 0) { fclose(fout); fout = fopen(wavFilePathChar, "w"); } if(fout == NULL){ return; } fwrite("RIFF", sizeof(char), 4,fout); fwrite(&totalSize, sizeof(int), 1, fout); fwrite("WAVE", sizeof(char), 4, fout); fwrite("fmt ", sizeof(char), 4, fout); fwrite(&chunkSize, sizeof(int),1,fout); fwrite(&audioFormat, sizeof(short), 1, fout); fwrite(&NumChannels, sizeof(short),1,fout); fwrite(&SamplingRate, sizeof(int), 1, fout); fwrite(&ByteRate, sizeof(int), 1, fout); fwrite(&BlockAlign, sizeof(short), 1, fout); fwrite(&BitsPerSample, sizeof(short), 1, fout); fwrite("data", sizeof(char), 4, fout); fwrite(&DataSize, sizeof(int), 1, fout); fclose(fout); } NSFileHandle *handle = [NSFileHandle fileHandleForUpdatingAtPath:self.wavFilePath]; [handle seekToEndOfFile]; // self.recordedData 为需要保存的pcm数据 @synchronized (self->_recordedTotalVoiceData) { [handle writeData:frame]; }
});
return nil;
}