Технические вопросы и ответы QA1865

Получение последовательности неподвижных изображений очень быстро с Основой AV на iOS

Q: Как я могу получить ряд неподвижных изображений в быстрой последовательности с помощью Основы AV?

A: Вызовите captureStillImageAsynchronously:completionHandler: метод неоднократно подряд, и они будут обслуживаться максимально быстро с результатами, поставленными к Вашему обработчику завершения. Однако существует предел тому, сколько выдающееся неподвижное изображение запрашивает, чтобы можно было стоять в очереди. Ограничение по току равняется 10. По 11-му выдающемуся запросу Вы получите ошибку.

Рекомендуемый подход должен использовать таймер, стреляющий в интервал о равном Вашему устройству activeVideoMaxFrameDuration как показано в Перечислении 1:

Перечисление 1  , Как получить много неподвижных изображений в быстрой последовательности с помощью таймера.

#import <AVFoundation/AVFoundation.h>
 
// Maximum number of queued still image requests.
int const MaxStillImageRequests = 10;
 
@interface MyController : UIViewController
 
@property dispatch_source_t timer;
@property int stillImageRequests; // Number of queued still image capture requests.
@property int imagesCaptured; // Number of still images captured.
 
-(void)captureImages:(int)count;
 
@end
 
...
 
//
// Capture still images in rapid succession
//
//     count = number of images to capture
//
-(void)captureImages:(int)count
{
    self.stillImageRequests = 0;
    self.imagesCaptured = 0;
 
    dispatch_queue_t timerQueue =
        dispatch_queue_create("timer queue",DISPATCH_QUEUE_SERIAL);
    // Create dispatch source that submits the event handler block based on a timer.
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,
                                        0, // unused
                                        DISPATCH_TIMER_STRICT,
                                        timerQueue);
    // Set the event handler block for the timer dispatch source.
    dispatch_source_set_event_handler(self.timer, ^{
 
        // This block will attempt to capture a new still image each time it is called.
 
        // Captured requested number of images?
        if (self.imagesCaptured >= count)
        {
            // Done capturing, kill the timer.
            dispatch_source_cancel(self.timer);
        }
        else if (self.stillImageRequests >= MaxStillImageRequests)
        {
           // Don't capture another image if the maximum
           // number of outstanding still image requests has
           // been exceeded.
        }
        else
        {
            self.stillImageRequests++;
            self.imagesCaptured++;
 
            // Capture a still image.
 
            AVCaptureStillImageOutput *stillImageOutput =
               <# a AVCaptureStillImageOutput #>;
            [stillImageOutput captureStillImageAsynchronouslyFromConnection:
                 [stillImageOutput connectionWithMediaType:AVMediaTypeVideo]
                     completionHandler:
             ^(CMSampleBufferRef imageDataSampleBuffer, NSError *error)
             {
                 self.stillImageRequests--;
 
                 if (error)
                 {
                     // Handle the error.
                 }
                 else if (imageDataSampleBuffer)
                 {
                     // Do something with the captured image.
                 }
             }];
        }
    });
 
    // Timer interval -- use your device’s activeVideoMaxFrameDuration
    uint64_t interval = 0.04;
    // Set timer start time and interval.
    dispatch_source_set_timer(self.timer,
                              dispatch_time(DISPATCH_TIME_NOW, 0), // start time
                              interval * NSEC_PER_SEC, // interval
                              interval * NSEC_PER_SEC); // leeway
    dispatch_resume(self.timer);
 
}


История версии документа


ДатаПримечания
17.07.2014

Новый документ, обсуждающий, как получить много неподвижных изображений очень быстро с Основой AV на iOS.