Search code examples
avfoundationcore-audiocmsamplebufferavassetreader

How to add a callback to AVAssetReader copyNextSampleBuffer?


I am trying to read audio frames and decode them with AVAssetReader. I want to be able to read the frames asynchronously and add some kind of callback when a sample buffer was read. So after calling:

...
[reader startReading];
CMSampleBufferRef sample = [readerOutput copyNextSampleBuffer];

I want to be able to refer to and process this sample from my callback. Is that possible? If not, can you suggest how I can do it using maybe other classes from AVFoundation/Core Audio?


Solution

  • -(CMSampleBufferRef)[AVAssetReaderOutput copyNextSampleBuffer] is synchronous and I don't see any alternatives.

    You can give it an asynchronous interface by doing something like this:

    dispatch_async(myDecodingDispatchQueue, ^{
      CMSampleBufferRef sampleBuffer;
      while ((sampleBuffer = [readerOutput copyNextSampleBuffer])) {
        dispatch_async(myDispatchQueue, ^{
           [myCallbackObject myCallbackWithSampleBuffer:sampleBuffer];
        });
      }
      // examine AVAssetReader.status here to see reason for stopping
    }