Skip to content

Instantly share code, notes, and snippets.

@michaelhenry
Last active October 21, 2019 06:57
Show Gist options
  • Save michaelhenry/88add95afce720baf0d172c695a6b468 to your computer and use it in GitHub Desktop.
Save michaelhenry/88add95afce720baf0d172c695a6b468 to your computer and use it in GitHub Desktop.
Wave Header (Audio)
@interface NSData (Wav)
- (NSData*) waveData;
@end
@implementation NSData (Wav)
- (NSData*) waveData {
NSMutableData *wavData = [NSMutableData data];
static constexpr char wavFormat[] =
"fmt " // field name
"\x10\x00\x00\x00" // field size (16 bytes)
"\x01\x00" // format tag (PCM)
"\x01\x00" // # of channels (1)
"\x80\x3e\x00\x00" // sample rate (16,000)
"\x00\x7d\x00\x00" // bytes per second (32,000)
"\x02\x00" // block alignment (2)
"\x10\x00"; // bits per sample (16)
auto dataSizeInBytes = 2*(self.length);
auto totalSizeInBytes = dataSizeInBytes + 36;
char wavPreamble[] = "RIFF@@@@WAVE";
wavPreamble[4] = static_cast<unsigned char>(totalSizeInBytes >> 0 );
wavPreamble[5] = static_cast<unsigned char>(totalSizeInBytes >> 8 );
wavPreamble[6] = static_cast<unsigned char>(totalSizeInBytes >> 16);
wavPreamble[7] = static_cast<unsigned char>(totalSizeInBytes >> 24);
char dataHeader[] = "data@@@@";
dataHeader[4] = static_cast<unsigned char>(dataSizeInBytes >> 0 );
dataHeader[5] = static_cast<unsigned char>(dataSizeInBytes >> 8 );
dataHeader[6] = static_cast<unsigned char>(dataSizeInBytes >> 16);
dataHeader[7] = static_cast<unsigned char>(dataSizeInBytes >> 24);
[wavData appendBytes:wavPreamble length:12];
[wavData appendBytes:wavFormat length: 24];
[wavData appendBytes:dataHeader length:8];
[wavData appendData:self];
return [wavData copy];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment