2011-12-15 1 views
0

Я переписываю аудио/видео с помощью AVfoudnation. и мне нужно воспроизвести звуки, используя системные звуки, прежде чем я начну захватывать видео/аудио. Это работает правильно в первый раз, но когда я пытаюсь сделать это во второй раз, система audi не воспроизводится. Я предполагаю, что что-то в AVfoundation не было выпущено правильно.Невозможно воспроизвести звуки системы после захвата аудио/видео

В моей заявке deletage, у меня есть этот код в методе applicationDidFinishLaunching:

VKRSAppSoundPlayer *aPlayer = [[VKRSAppSoundPlayer alloc] init]; 
[aPlayer addSoundWithFilename:@"sound1" andExtension:@"caf"]; 
self.appSoundPlayer = aPlayer; 
[aPlayer release]; 

, а также этот метод

- (void)playSound:(NSString *)sound 
{ 
    [appSoundPlayer playSound:sound]; 
} 

Как вы можете видеть, я использую VKRSAppSoundPlayer, который прекрасно работает!

В свете, у меня есть этот код:

- (void) startSession 
{ 
    self.session = [[AVCaptureSession alloc] init]; 

    [session beginConfiguration]; 
    if([session canSetSessionPreset:AVCaptureSessionPreset640x480]) 
     session.sessionPreset = AVCaptureSessionPresetMedium; 

    [session commitConfiguration]; 


    CALayer *viewLayer = [videoPreviewView layer]; 

    AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session]; 

    captureVideoPreviewLayer.frame = viewLayer.bounds; 

    [viewLayer addSublayer:captureVideoPreviewLayer]; 

    self.videoInput = [AVCaptureDeviceInput deviceInputWithDevice:[self frontFacingCameraIfAvailable] error:nil]; 
    self.audioInput = [AVCaptureDeviceInput deviceInputWithDevice:[self audioDevice] error:nil]; 

    if(videoInput){ 
     self.videoOutput = [[AVCaptureMovieFileOutput alloc] init]; 

     [session addOutput:videoOutput]; 
     //[videoOutput release]; 

     if([session canAddInput:videoInput]){ 
      //[session beginConfiguration]; 
      [session addInput:videoInput]; 

     } 
     //[videoInput release]; 

     [session removeInput:[self audioInput]]; 
     if([session canAddInput:audioInput]){ 
      [session addInput:audioInput]; 
     } 
     //[audioInput release]; 


     if([session canAddInput:audioInput]) 
      [session addInput:audioInput]; 


     NSLog(@"startRunning!"); 
     [session startRunning]; 

     [self startRecording]; 


     if(![self recordsVideo]) 
      [self showAlertWithTitle:@"Video Recording Unavailable" msg:@"This device can't record video."]; 

    } 
} 

- (void) stopSession 
{ 
    [session stopRunning]; 
    [session release]; 
} 


- (AVCaptureDevice *)frontFacingCameraIfAvailable 
{ 
    NSArray *videoDevices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]; 
    AVCaptureDevice *captureDevice = nil; 

    Boolean cameraFound = false; 

    for (AVCaptureDevice *device in videoDevices) 
    { 
     NSLog(@"1 frontFacingCameraIfAvailable %d", device.position); 
     if (device.position == AVCaptureDevicePositionBack){ 
      NSLog(@"1 frontFacingCameraIfAvailable FOUND"); 

      captureDevice = device; 
      cameraFound = true; 
      break; 
     } 
    } 

    if(cameraFound == false){ 
     for (AVCaptureDevice *device in videoDevices) 
     { 
      NSLog(@"2 frontFacingCameraIfAvailable %d", device.position); 
      if (device.position == AVCaptureDevicePositionFront){ 
       NSLog(@"2 frontFacingCameraIfAvailable FOUND"); 

       captureDevice = device; 
       break; 
      } 
     } 
    } 

    return captureDevice; 
} 

- (AVCaptureDevice *) audioDevice 
{ 
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio]; 
    if ([devices count] > 0) { 
     return [devices objectAtIndex:0]; 
    } 
    return nil; 
} 

- (void) startRecording 
{ 
#if _Multitasking_ 
    if ([[UIDevice currentDevice] isMultitaskingSupported]) { 
     [self setBackgroundRecordingID:[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{}]]; 
    } 
#endif 

    [videoOutput startRecordingToOutputFileURL:[self generatenewVideoPath] 
          recordingDelegate:self]; 
} 

- (void) stopRecording 
{ 
    [videoOutput stopRecording]; 

} 

- (void)captureOutput:(AVCaptureFileOutput *)captureOutput 
didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL 
     fromConnections:(NSArray *)connections error:(NSError *)error 
{ 
    NSFileManager *man = [[NSFileManager alloc] init]; 
    NSDictionary *attrs = [man attributesOfItemAtPath: [outputFileURL path] error: NULL]; 
    NSString *fileSize = [NSString stringWithFormat:@"%llu", [attrs fileSize]]; 


    // close this screen 
    [self exitScreen]; 
} 

-(BOOL)recordsVideo 
{ 
    AVCaptureConnection *videoConnection = [AVCamUtilities connectionWithMediaType:AVMediaTypeVideo 
                    fromConnections:[videoOutput connections]]; 
    return [videoConnection isActive]; 
} 

-(BOOL)recordsAudio 
{ 
    AVCaptureConnection *audioConnection = [AVCamUtilities connectionWithMediaType:AVMediaTypeAudio 
                    fromConnections:[videoOutput connections]]; 
    return [audioConnection isActive]; 
} 

Если я [выпуск видеоввода]; и [выпуск аудиовхода]; У меня плохая ошибка доступа. поэтому их прокомментировали. Это может быть частью проблемы.

Если я попытаюсь воспроизвести звук системы n раз, это сработает, но если я сначала займусь скриптом записи, он не будет работать после этого.

Любые идеи?

+0

вам нужно лучше понять, что означает self.iVar, и что означает релиз. релиз уменьшает счетчик удержания, который, если 0 делает объект подходящим для освобождения. Использование self.iVar (при условии, что вы объявили его как свойство) сохраняет этот iVar, поэтому вы можете сразу его освободить. Но я не думаю, что это ваша проблема с аудио. – Rayfleck

ответ

0

Правильный способ освободить AVCaptureSession заключается в следующем:

- (void) destroySession { 

    // Notify the view that the session will end 
    if ([delegate respondsToSelector:@selector(captureManagerSessionWillEnd:)]) { 
     [delegate captureManagerSessionWillEnd:self]; 
    } 

    // remove the device inputs 
    [session removeInput:[self videoInput]]; 
    [session removeInput:[self audioInput]]; 

    // release 
    [session release]; 

    // remove AVCamRecorder 
    [recorder release]; 

    // Notify the view that the session has ended 
    if ([delegate respondsToSelector:@selector(captureManagerSessionEnded:)]) { 
     [delegate captureManagerSessionEnded:self]; 
    } 
} 

Если у вас возникли какие-то проблемы высвобождения (плохой доступ), я могу порекомендовать принимать код из текущей «грязной» проекта в какой-то другой новый проект и отладить проблему там.

Когда у меня была схожая проблема, я просто сделал это. Я поделился им с Github, вы можете найти этот проект полезным: AVCam-CameraReleaseTest