title: Using CMSampleTimingInfo, CMSampleBuffer and AudioBufferList from raw PCM 16000 sample rate stream
body: <p>I recevie audio data and size from outside, the audio appears to be linear PCM, signed int16, but when recording this using an AssetWriter it saves to the audio file highly distorted and higher pitch.</p>
  
  <pre><code>#define kSamplingRate       16000
  #define kNumberChannels     1
  
  UInt32 framesAlreadyWritten = 0;
  
  -(AudioStreamBasicDescription) getAudioFormat {
  AudioStreamBasicDescription format;
  format.mSampleRate = kSamplingRate;
  format.mFormatID = kAudioFormatLinearPCM;
  format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  format.mChannelsPerFrame = 1;  // mono
  format.mBitsPerChannel = 16;
  format.mBytesPerFrame = sizeof(SInt16);
  format.mFramesPerPacket = 1;
  format.mBytesPerPacket = format.mBytesPerFrame * format.mFramesPerPacket;
  format.mReserved = 0;
  return format;
  }
  
   - (CMSampleBufferRef)createAudioSample:(const void *)audioData frames:    (UInt32)len {
  
  AudioStreamBasicDescription asbd = [self getAudioFormat];
  
  CMSampleBufferRef buff = NULL;
  static CMFormatDescriptionRef format = NULL;
  OSStatus error = 0;
  
  if(format == NULL) {
      AudioChannelLayout acl;
      bzero(&amp;acl, sizeof(acl));
      acl.mChannelLayoutTag = kAudioChannelLayoutTag_Mono;
      error = CMAudioFormatDescriptionCreate(kCFAllocatorDefault, &amp;asbd, sizeof(acl), &amp;acl, 0, NULL, NULL, &amp;format);
  }
  
  CMTime duration = CMTimeMake(1, kSamplingRate);
  CMTime pts = CMTimeMake(framesAlreadyWritten, kSamplingRate);
  NSLog(@"-----------pts");
  CMTimeShow(pts);
  CMSampleTimingInfo timing = {duration , pts, kCMTimeInvalid };
  error = CMSampleBufferCreate(kCFAllocatorDefault, NULL, false, NULL, NULL, format, len, 1, &amp;timing, 0, NULL, &amp;buff);
  framesAlreadyWritten += len;
  
  if (error) {
      NSLog(@"CMSampleBufferCreate returned error: %ld", (long)error);
      return NULL;
  }
  
  AudioBufferList audioBufferList;
  audioBufferList.mNumberBuffers = 1;
  audioBufferList.mBuffers[0].mNumberChannels = asbd.mChannelsPerFrame;
  audioBufferList.mBuffers[0].mDataByteSize = (UInt32)(number_of_frames * audioFormat.mBytesPerFrame);
  audioBufferList.mBuffers[0].mData = audioData;
  
  error = CMSampleBufferSetDataBufferFromAudioBufferList(buff, kCFAllocatorDefault, kCFAllocatorDefault, 0, &amp;audioBufferList);
  if(error) {
      NSLog(@"CMSampleBufferSetDataBufferFromAudioBufferList returned error: %ld", (long)error);
      return NULL;
  }
  return buff;
  }
  </code></pre>