Skip to content

Instantly share code, notes, and snippets.

@kaaaaai
Created August 14, 2023 12:43
Show Gist options
  • Save kaaaaai/1e9007a0be49e2b7f996fbed8ab091ea to your computer and use it in GitHub Desktop.
Save kaaaaai/1e9007a0be49e2b7f996fbed8ab091ea to your computer and use it in GitHub Desktop.
wave 文件头创建
- (NSData *)generateWavHeader:(NSUInteger)waveLength {
// 定义 WAV 文件的参数
NSUInteger sampleRate = 16000; // 采样率
NSUInteger bitsPerSample = 16; // 采样位数
NSUInteger numChannels = 1; // 声道数(单声道)
// 计算数据长度(不包括 WAV 文件头)
NSUInteger dataLength = waveLength; // 数据长度(根据实际情况赋值)
// 计算文件总长度(包括 WAV 文件头)
NSUInteger totalLength = dataLength + 44;
// 创建一个可变的 NSMutableData对象,用于存储 WAV 文件头的数据
NSMutableData *headerData = [NSMutableData dataWithLength:44];
// Chunk ID(RIFF 标志)
NSString *chunkID = @"RIFF";
[headerData replaceBytesInRange:NSMakeRange(0, 4) withBytes:[chunkID UTF8String]];
// Chunk Size(文件总长度减去 8)
NSUInteger chunkSize = totalLength - 8;
[headerData replaceBytesInRange:NSMakeRange(4, 4) withBytes:&chunkSize];
// Format(WAVE 标志)
NSString *format = @"WAVE";
[headerData replaceBytesInRange:NSMakeRange(8, 4) withBytes:[format UTF8String]];
// Subchunk1 ID(fmt 标志)
NSString *subchunk1ID = @"fmt ";
[headerData replaceBytesInRange:NSMakeRange(12, 4) withBytes:[subchunk1ID UTF8String]];
// Subchunk1 Size(16)
NSUInteger subchunk1Size = 16;
[headerData replaceBytesInRange:NSMakeRange(16, 4) withBytes:&subchunk1Size];
// Audio Format(PCM 格式,值为 1)
short audioFormat = 1;
[headerData replaceBytesInRange:NSMakeRange(20, 2) withBytes:&audioFormat];
// Num Channels(声道数)
[headerData replaceBytesInRange:NSMakeRange(22, 2) withBytes:&numChannels];
// Sample Rate(采样率)
[headerData replaceBytesInRange:NSMakeRange(24, 4) withBytes:&sampleRate];
// Byte Rate(每秒字节数)
NSUInteger byteRate = sampleRate * numChannels * bitsPerSample / 8;
[headerData replaceBytesInRange:NSMakeRange(28, 4) withBytes:&byteRate];
// Block Align(每个样本的字节数)
short blockAlign = numChannels * bitsPerSample / 8;
[headerData replaceBytesInRange:NSMakeRange(32, 2) withBytes:&blockAlign];
// Bits Per Sample(采样位数)
[headerData replaceBytesInRange:NSMakeRange(34, 2) withBytes:&bitsPerSample];
// Subchunk2 ID(data 标志)
NSString *subchunk2ID = @"data";
[headerData replaceBytesInRange:NSMakeRange(36, 4) withBytes:[subchunk2ID UTF8String]];
// Subchunk2 Size(数据长度)
[headerData replaceBytesInRange:NSMakeRange(40, 4) withBytes:&dataLength];
// 现在,你可以将 headerData 数据追加到音频数据后面,作为 WAV 文件的完整数据
return headerData;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment