Skip to content

Instantly share code, notes, and snippets.

@olenhad
Last active January 2, 2021 02:49
Show Gist options
  • Save olenhad/cc3101eb96fb7179a629f78bd9f0f00d to your computer and use it in GitHub Desktop.
Save olenhad/cc3101eb96fb7179a629f78bd9f0f00d to your computer and use it in GitHub Desktop.
Combining AVAudioPCMBuffers. Assumes non interleaved format
@implementation AVAudioPCMBuffer (LiveAdditions)
- (AVAudioPCMBuffer *)combineWithBuffer:(AVAudioPCMBuffer *)buffer {
if (![buffer.format isEqual:self.format]) {
return nil;
}
AVAudioPCMBuffer *combined = [[AVAudioPCMBuffer alloc] initWithPCMFormat:self.format frameCapacity:self.frameCapacity + buffer.frameCapacity];
combined.frameLength = self.frameLength + buffer.frameLength;
if (self.int16ChannelData && combined.int16ChannelData) {
for (AVAudioChannelCount i = 0; i < self.format.channelCount; i++) {
memcpy(combined.int16ChannelData[i], self.int16ChannelData[i], self.frameLength * self.format.streamDescription->mBytesPerFrame);
memcpy(combined.int16ChannelData[i] + self.frameLength, buffer.int16ChannelData[i], buffer.frameLength * self.format.streamDescription->mBytesPerFrame);
}
}
else if (self.floatChannelData && combined.floatChannelData) {
for (AVAudioChannelCount i = 0; i < self.format.channelCount; i++) {
memcpy(combined.floatChannelData[i], self.floatChannelData[i], self.frameLength * self.format.streamDescription->mBytesPerFrame);
memcpy(combined.floatChannelData[i] + self.frameLength, buffer.floatChannelData[i], buffer.frameLength * self.format.streamDescription->mBytesPerFrame);
}
}
else if (self.int32ChannelData && combined.int32ChannelData) {
for (AVAudioChannelCount i = 0; i < self.format.channelCount; i++) {
memcpy(combined.int32ChannelData[i], self.int32ChannelData[i], self.frameLength * self.format.streamDescription->mBytesPerFrame);
memcpy(combined.int32ChannelData[i] + self.frameLength, buffer.int32ChannelData[i], buffer.frameLength * self.format.streamDescription->mBytesPerFrame);
}
}
else {
NSParameterAssert(NO);
}
return combined;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment