title: Audio is not being recorded using AVAssetWrite
body: <p>I am trying to record audio in a file for 14 days. I am getting audio data in PCM format through screen mirroring in which audio is received and from this I am converting it to <code>CMSampleBuffer</code> using this code </p>
  
  <pre><code>-(void)createAudioSampleBufferFromData:(uint8_t*)buf withSize:(uint32_t)buflen timeStamp:(double)timeStamp{
      OSStatus status;
      AudioStreamBasicDescription monoStreamFormat;
  
      memset(&amp;monoStreamFormat, 0, sizeof(monoStreamFormat));
      monoStreamFormat.mFormatID         = kAudioFormatLinearPCM;
      monoStreamFormat.mSampleRate       = 44100;
      monoStreamFormat.mChannelsPerFrame = 2;
      monoStreamFormat.mBitsPerChannel   = 16;
      monoStreamFormat.mFramesPerPacket  = 1;  // uncompressed audio
      monoStreamFormat.mBytesPerFrame    =monoStreamFormat.mChannelsPerFrame * monoStreamFormat.mBitsPerChannel/8;
      monoStreamFormat.mBytesPerPacket   = monoStreamFormat.mBytesPerFrame * monoStreamFormat.mFramesPerPacket;
      monoStreamFormat.mFormatFlags      = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  
      CMFormatDescriptionRef format = NULL;
      status = CMAudioFormatDescriptionCreate(kCFAllocatorDefault, &amp;monoStreamFormat, 0, NULL, 0, NULL, NULL, &amp;format);
      if (status != noErr) {
          // really shouldn't happen
          return;
      }
  
      long blockLength = buflen;
  
      CMSampleBufferRef sampleBuffer = NULL;
      CMBlockBufferRef blockBuffer = NULL;
  
      status = CMBlockBufferCreateWithMemoryBlock(kCFAllocatorDefault, buf,  // memoryBlock to hold buffered data
                                              blockLength,  // block length of the mem block in bytes.
                                              kCFAllocatorDefault, NULL,
                                              0, // offsetToData
                                              blockLength,   // dataLength of relevant bytes, starting at offsetToData
                                              0, &amp;blockBuffer);
  
  
      if(status == noErr)
      {
  
          CMSampleTimingInfo timings = {CMTimeMake(1, 44100.0), CMClockGetTime(CMClockGetHostTimeClock()), kCMTimeInvalid };
  
          const size_t sampleSize = blockLength;
          status = CMSampleBufferCreate(kCFAllocatorDefault,
                                    NULL, true, NULL, NULL,
                                    format, 1, 0, &amp;timings, 1,
                                    &amp;sampleSize, &amp;sampleBuffer);
           CMItemCount itemCount = CMSampleBufferGetNumSamples(sampleBuffer);
  
          [self notifyAudioBufferReceived:sampleBuffer];
  //        if(blockBuffer)
  //            CFRelease(blockBuffer);
  
      }
  }
  </code></pre>
  
  <p>And in following method this <code>CMSampleBuffers</code> are receiving:</p>
  
  <pre><code>- (void)airPlayServer:(id)server audioBufferReceived:(CMSampleBufferRef)buffer {
      if(recordingStarted){
          [decoderAndRecorder.recorder newAudioSample:buffer];
      }
  //    CFRelease(buffer);
  }
  </code></pre>
  
  <p>from here these buffers go to AVAssetWriter class where I am appending these buffer to record audio into file. AVAssetWriter class is following:</p>
  
  <pre><code>- (instancetype)init
  {
      self = [super init];
      if (self) {
          // Create asset writer
  
          dateString = [self dateInString];
  
          NSString *documents = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex: 0];
          filePath = [documents stringByAppendingPathComponent:[NSString stringWithFormat:@"screen recording - %@.caf",dateString]];
  
          if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
              [[NSFileManager defaultManager] removeItemAtPath:filePath
                                                     error:nil];
          }
  
      NSLog(@"%@", filePath);
          NSError *error = nil;
  
      _assetWriter = [[AVAssetWriter alloc] initWithURL:[NSURL fileURLWithPath:filePath]
                                               fileType:AVFileTypeCoreAudioFormat
                                                  error:&amp;error];
  
          AudioChannelLayout acl;
          memset(&amp;acl,0, sizeof(acl));
          acl.mChannelLayoutTag = kAudioChannelLayoutTag_Mono;
  
          NSDictionary* audioOutputSettings = nil;
  
          audioOutputSettings = [ NSDictionary dictionaryWithObjectsAndKeys:
                                [ NSNumber numberWithInt: kAudioFormatLinearPCM ], AVFormatIDKey,
                                [ NSNumber numberWithFloat: 44100.0 ], AVSampleRateKey,
                                [ NSNumber numberWithInt: 1 ], AVNumberOfChannelsKey,
                                [ NSData dataWithBytes: &amp;acl length: sizeof( acl ) ], AVChannelLayoutKey,
                                [ NSNumber numberWithInt: 16 ], AVLinearPCMBitDepthKey,
                                [NSNumber numberWithBool:NO], AVLinearPCMIsNonInterleaved,
                                [NSNumber numberWithBool:NO], AVLinearPCMIsFloatKey,
                                [NSNumber numberWithBool:NO], AVLinearPCMIsBigEndianKey,
                                 nil ];
  
  
          _audioWriterInput = [[AVAssetWriterInput alloc]
                                initWithMediaType: AVMediaTypeAudio
                                outputSettings: audioOutputSettings ];
  
          _audioWriterInput.expectsMediaDataInRealTime = YES;
          NSParameterAssert(_audioWriterInput);
          NSParameterAssert([_assetWriter canAddInput:_audioWriterInput]);
          [_assetWriter addInput:_audioWriterInput];          
      }
  
  }
  return self;
  }
  
  -(void)startSession{
      //This is vedio recorder code
      _isStarted =[_assetWriter startWriting];
      if(_isStarted)
      {
          NSLog(@"======== Session started");
          [_assetWriter startSessionAtSourceTime:_startingTime];
      }
      else {
          NSLog(@"======== Session failed : %@", _assetWriter.error);
      }
  }
  
  -(void)endSession
  {
      _isStarted = NO;
  
      [_audioWriterInput markAsFinished];
      [_assetWriter finishWritingWithCompletionHandler:^{
          NSLog(@"====== File Save Successfully =======");
  
      }];
  }
  
  - (void)newAudioSample:(CMSampleBufferRef)sampleBuffer
  {
      if (_isStarted) {
          if (_videoWriter.status == AVAssetWriterStatusWriting) {
  //            if(_audioWriterInput.readyForMoreMediaData){
              //NSLog(@"Warning: writer status is %d", _videoWriter.status)
  
                  if(sampleBuffer){
                      if (![_audioWriterInput appendSampleBuffer:sampleBuffer]) {
                          NSLog(@"Unable to write to audio input");
                      }else{
                          NSLog(@"====Audio is being recorded===");
                      }
  
                  }
  
  //            }
          }else if(_videoWriter.status == AVAssetWriterStatusFailed){
              NSLog(@"&lt;----- Appending failed -----&gt;");
              NSLog(@"Error: %@", _videoWriter.error);
  
          }
      }
  }
  </code></pre>
  
  <p>That's all. File is created but with zero bytes. No data is written in it. Please help with with this problem.</p>