public void StartWithAsync(TaskCompletionSource <object> completionSource, AVReaderWriter handler) { if (_completionSource != null) { throw new InvalidProgramException(); } _completionSource = completionSource; _assetWriterInput.RequestMediaData(_serializationQueue, () => { if (_finished) { return; } bool completedOrFailed = false; // Read samples in a loop as long as the asset writer input is ready while (_assetWriterInput.ReadyForMoreMediaData && !completedOrFailed) { bool success; using (CMSampleBuffer sampleBuffer = _assetReaderOutput.CopyNextSampleBuffer()) { if (sampleBuffer == null) { completedOrFailed = true; continue; } if (_adaptor != null) { CMTime presentationTime = sampleBuffer.PresentationTimeStamp; using (CVPixelBuffer writerBuffer = _adaptor.PixelBufferPool.CreatePixelBuffer()) { handler.DidReadAndWriteSampleBuffer(this, sampleBuffer, writerBuffer); success = _adaptor.AppendPixelBufferWithPresentationTime(writerBuffer, presentationTime); } } else { handler.DidReadSampleBuffer(this, sampleBuffer); success = _assetWriterInput.AppendSampleBuffer(sampleBuffer); } } completedOrFailed = !success; } if (completedOrFailed) { CompleteTaskIfNecessary(); } }); }
void WriteSampleBuffer(CMSampleBuffer sampleBuffer, NSString mediaType) { if (assetWriter.Status == AVAssetWriterStatus.Unknown) { if (assetWriter.StartWriting()) { assetWriter.StartSessionAtSourceTime(sampleBuffer.OutputPresentationTimeStamp); } else { ShowError(assetWriter.Error); } } if (assetWriter.Status == AVAssetWriterStatus.Writing) { if (mediaType == AVMediaType.Video) { if (assetWriterVideoIn.ReadyForMoreMediaData) { if (!assetWriterVideoIn.AppendSampleBuffer(sampleBuffer)) { ShowError(assetWriter.Error); } } } else if (mediaType == AVMediaType.Audio) { if (assetWriterAudioIn.ReadyForMoreMediaData) { if (!assetWriterAudioIn.AppendSampleBuffer(sampleBuffer)) { ShowError(assetWriter.Error); } } } } }