Reading Samples with AVAssetReader

How do you read samples through AVAssetReader? I found examples of duplication or mixing using AVAssetReader, but these loops are always controlled by the AVAssetWriter contour. Is it possible to simply create an AVAssetReader and read it, having received each sample?

Thank.

+10
objective-c iphone cocoa-touch avfoundation
Oct 29 '10 at 5:23
source share
2 answers

It is not clear from your question whether you are talking about video samples or audio samples. To read the video samples, you need to do the following:

  • Build AVAssetReader:

    asset_reader = [[AVAssetReader alloc] initWithAsset:asset error:&error]; (error checking goes here)

  • Get a video track from your resource:

    NSArray* video_tracks = [asset tracksWithMediaType:AVMediaTypeVideo]; AVAssetTrack* video_track = [video_tracks objectAtIndex:0];

  • Set the desired video format:

      NSMutableDictionary * dictionary = [[NSMutableDictionary alloc] init];
     [dictionary setObject: [NSNumber numberWithInt: <format code from CVPixelBuffer.h>] forKey: (NSString *) kCVPixelBufferPixelFormatTypeKey]; 

    Please note that some video formats just don't work, and if you do something in real time, some video formats work better than others (BGRA is faster than ARGB, for example).

  • Create the actual track output and add it to the asset reader:

      AVAssetReaderTrackOutput * asset_reader_output = [[AVAssetReaderTrackOutput alloc] initWithTrack: video_track outputSettings: dictionary];
     [asset_reader addOutput: asset_reader_output]; 
  • Kill the asset reader:

    [asset_reader startReading];

  • Read samples:

     CMSampleBufferRef buffer;
     while ([asset_reader status] == AVAssetReaderStatusReading)
           buffer = [asset_reader_output copyNextSampleBuffer];
    
+24
Nov 18 '10 at 15:03
source share

Damian's answer worked for me with the video and one minor modification: in step 3, I believe that the dictionary should be changed:

 NSMutableDictionary* dictionary = [[NSMutableDictionary alloc] init]; 
+2
May 18 '11 at 11:10
source share



All Articles