AVAssetWriterInput

Я пытаюсь получить ввод с камеры и записать данные на диск с помощью avassetwriter. Из делегата просто видно, что avassetwriterinputpixelbufferadator не может добавить данные. я не знаю почему

- (NSURL*) assetURL{
 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
 NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
 NSString *filePath = [basePath stringByAppendingPathComponent:@"videoOutput"];

 return [NSURL fileURLWithPath:filePath];
}



- (id) init {
 if(![super init]) return nil;

 self.captureSession = [[c alloc] init];
 self.captureSession.sessionPreset = AVCaptureSessionPresetHigh; 

 // HIGH: 640 x 480
 // MEDIUM: 360 x 480
 // LOW: 192 x 144

 [self loadVideoInput];
 [self loadVideoOutput];
 [self loadPreviewLayer];
 [self loadWriter];



 return self;
}
- (void) loadVideoInput{


 AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
 NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *device in devices) {
        if (device.position == AVCaptureDevicePositionFront) {
            videoDevice = device;
   break;
        }
    }



 if ( videoDevice ) {
  NSError *error;
  AVCaptureDeviceInput *videoIn = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error];
  if ( !error ) {
   if ([self.captureSession canAddInput:videoIn]) 
    [self.captureSession addInput:videoIn];
   else NSLog(@"Couldn't add video input");  
  } else NSLog(@"Couldn't create video input");
 } else NSLog(@"Couldn't create video capture device");
}
- (void) loadVideoOutput{

 AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
 output.alwaysDiscardsLateVideoFrames = YES;

 [output setSampleBufferDelegate:self queue:dispatch_get_main_queue()];

 //dispatch_queue_t queue = dispatch_queue_create("myQueue", NULL);
 //[output setSampleBufferDelegate:self queue:queue];
 //dispatch_release(queue);


 //output.minFrameDuration = CMTimeMake(15, 1); // If you wish to cap the frame rate to a known value, such as 15 fps, set 
 [output setVideoSettings:[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_32BGRA] forKey:(id)kCVPixelBufferPixelFormatTypeKey]]; // BGRA is necessary for manual preview



 if ([self.captureSession canAddOutput:videoOut]) 
  [self.captureSession addOutput:videoOut]; 
 else 
  NSLog(@"Couldn't add video output");
 //[self.captureSession addOutput:output];
 [output release];

}
- (void) loadPreviewLayer{
 previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];
 previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
}

- (void) loadWriter{



 NSError *error = nil;
 videoWriter = [[AVAssetWriter alloc] initWithURL:[self assetURL] fileType:AVFileTypeQuickTimeMovie error:&error];
 NSParameterAssert(videoWriter);

 NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:
           AVVideoCodecH264, AVVideoCodecKey,
           [NSNumber numberWithInt:640], AVVideoWidthKey,
           [NSNumber numberWithInt:480], AVVideoHeightKey,
           nil];
 writerInput = [[AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:videoSettings] retain];
 writerInput.expectsMediaDataInRealTime = YES;
 NSParameterAssert(writerInput);
 NSParameterAssert([videoWriter canAddInput:writerInput]);
 [videoWriter addInput:writerInput];

 currentTime = kCMTimeZero;

 adaptor = [[AVAssetWriterInputPixelBufferAdaptor assetWriterInputPixelBufferAdaptorWithAssetWriterInput:writerInput sourcePixelBufferAttributes:nil] retain];


 NSLog(@"Error? %@",error);

}


- (void) captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {

 if(recording){


  CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer); 
  currentTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);


  // STUFF ISN'T WORKING HERE


  BOOL success = [adaptor appendPixelBuffer:imageBuffer withPresentationTime:currentTime];
  NSLog(@"%@",success ? @"YES" : @"NO");
 }



}


- (void) startRecording{
 [videoWriter startWriting];
 [videoWriter startSessionAtSourceTime:currentTime];
 recording = YES;

}

- (void) stopRecording{
 recording = NO;
 [writerInput markAsFinished];
 [videoWriter endSessionAtSourceTime:currentTime];
 [videoWriter finishWriting];
}

person devinross    schedule 12.11.2010    source источник
comment
Вы решили эту проблему? И если да, то какое было решение?   -  person zakdances    schedule 02.08.2012


Ответы (2)


Вам нужно каждый раз удалять существующий файл ("filePath" в вашем случае), пытаясь записать видео.

person Matic Oblak    schedule 01.12.2010

[adaptor appendPixelBuffer:imageBuffer withPresentationTime:currentTime];

возможно, вам нужно управлять временем видео самостоятельно, вы получаете currentTime из sampleBuffer, это не совсем время видео. попытаться накопить предварительный кадр времени захвата

person mike    schedule 09.10.2011