Created
October 30, 2017 17:23
-
-
Save brennanMKE/b7de13a02c0a49e165214558be62f47c to your computer and use it in GitHub Desktop.
Create a silent audio file with Objective-C
This file contains hidden or 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
- (void)createSilentAudioFileAtURL:(NSURL *)fileURL durationInMilliseconds:(NSInteger)durationInMilliseconds { | |
AudioFileID mRecordFile; | |
AudioStreamBasicDescription audioFormat; | |
audioFormat.mSampleRate = 44100.00; | |
audioFormat.mFormatID = kAudioFormatLinearPCM; | |
audioFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked; | |
audioFormat.mFramesPerPacket = 1; | |
audioFormat.mChannelsPerFrame = 2; | |
audioFormat.mBitsPerChannel = sizeof(short) * 8; | |
audioFormat.mBytesPerPacket = sizeof(short) * 2; | |
audioFormat.mBytesPerFrame = sizeof(short) * 2; | |
audioFormat.mReserved = 0; | |
OSStatus status = AudioFileCreateWithURL((__bridge CFURLRef)fileURL, kAudioFileCAFType, &audioFormat, kAudioFileFlags_EraseFile, &mRecordFile); | |
NSAssert(status != kAudioFileUnsupportedDataFormatError, @"Unsupported data format error."); | |
NSAssert(status == noErr, @"Failed to create audio file."); | |
double intervalInSamples = 0.5; | |
intervalInSamples *= audioFormat.mSampleRate * audioFormat.mChannelsPerFrame; | |
double durationInSeconds = (double)durationInMilliseconds / 1000.0; | |
int inNumberFrames = (intervalInSamples * durationInSeconds); | |
UInt32 frameBuffer[inNumberFrames]; | |
for (int i = 0; i < inNumberFrames; i++) { frameBuffer[i] = 0; } | |
UInt32 bytesToWrite = inNumberFrames * sizeof(uint32_t); | |
status = AudioFileWriteBytes(mRecordFile, false, 0, &bytesToWrite, &frameBuffer); | |
NSAssert(status == noErr, @"Failed to write bytes to audio file."); | |
status = AudioFileClose(mRecordFile); | |
NSAssert(status == noErr, @"Failed to close audio file."); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome, thank you so much:)