Last active
August 14, 2023 06:44
-
-
Save kaaaaai/032c20e329f3240a5f507ebd4af0dbb2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 假设有一个名为 "floatArray" 的 float 数组和 "arrayLength" 表示数组长度 | |
NSString *filePath = @"/path/to/file.wav"; // 指定保存 WAV 文件的路径 | |
// 打开文件用于写入 | |
NSOutputStream *outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO]; | |
[outputStream open]; | |
// 构建 WAV 文件头信息 | |
// WAV 文件头的具体格式请根据需要进行调整,以下示例仅提供基本结构 | |
// 更多关于 WAV 文件格式的信息可以参考相应的规范 | |
// WAV 文件头信息 | |
struct { | |
char chunkID[4]; | |
uint32_t chunkSize; | |
char format[4]; | |
char subchunk1ID[4]; | |
uint32_t subchunk1Size; | |
uint16_t audioFormat; | |
uint16_t numChannels; | |
uint32_t sampleRate; | |
uint32_t byteRate; | |
uint16_t blockAlign; | |
uint16_t bitsPerSample; | |
char subchunk2ID[4]; | |
uint32_t subchunk2Size; | |
} wavHeader; | |
// 填充 WAV 文件头信息 | |
memcpy(wavHeader.chunkID, "RIFF", 4); | |
wavHeader.chunkSize = sizeof(wavHeader) - 8 + arrayLength * sizeof(float); | |
memcpy(wavHeader.format, "WAVE", 4); | |
memcpy(wavHeader.subchunk1ID, "fmt ", 4); | |
wavHeader.subchunk1Size = 16; | |
wavHeader.audioFormat = 3; // IEEE float | |
wavHeader.numChannels = 1; // 单声道 | |
wavHeader.sampleRate = 44100; // 采样率 | |
wavHeader.byteRate = wavHeader.sampleRate * sizeof(float); | |
wavHeader.blockAlign = sizeof(float); | |
wavHeader.bitsPerSample = sizeof(float) * 8; | |
memcpy(wavHeader.subchunk2ID, "data", 4); | |
wavHeader.subchunk2Size = arrayLength * sizeof(float); | |
// 写入 WAV 文件头 | |
[outputStream write:(const uint8_t *)&wavHeader maxLength:sizeof(wavHeader)]; | |
// 将 float 数组的内容写入文件 | |
[outputStream write:(const uint8_t *)floatArray maxLength:arrayLength * sizeof(float)]; | |
// 关闭文件写入器 | |
[outputStream close]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment