Pregunta

Estoy intentando configurar un controlador básico que grabará la entrada de audio del usuario (voz). Sin embargo, el método prepareToRecord de AVAudioRecorder está fallando y no puedo entender por qué. He configurado la sesión de audio en mi delegado de aplicaciones y no recibo ningún error cuando instancia la instancia de AVAudioRecorder:

// Fragmento de delegado de aplicación

AVAudioSession* audioSession = [AVAudioSession sharedInstance];
NSError* audioSessionError   = nil;

[audioSession setCategory: AVAudioSessionCategoryPlayAndRecord
                  error: &audioSessionError];

  if (audioSessionError) {
    NSLog (@"Error setting audio category: %@", [audioSessionError localizedDescription]); 
} else {
  NSLog(@"No session errors for setting category");
}

[audioSession setActive:YES error:&audioSessionError];

if (audioSessionError) {
  NSLog (@"Error activating audio session: %@", [audioSessionError localizedDescription]); 
} else {
NSLog(@"no session errors for setActive");
}

// VER LA CARGA EN EL CONTROLADOR DE GRABACIÓN

- (void)viewDidLoad {

self.navigationItem.title = [NSString stringWithFormat:@"%@", [[MyAppDelegate loadApplicationPlist] valueForKey:@"recorderViewTitle"]];

self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone 
                                                                                     target:self 
                                                                                     action:@selector(dismiss)];

[self alertIfNoAudioInput];

 [self createAVAudioRecorder];

 minutesSecondsFormatter = [[SimpleMinutesSecondsFormatter alloc] init];
currentTimeUpdateTimer  = [NSTimer scheduledTimerWithTimeInterval:0.1
                                                        target:self selector:@selector(updateAudioDisplay)
                                                       userInfo:NULL repeats:YES];

[super viewDidLoad];
}

// CREAR UN GRABADOR DE DISPONIBILIDAD

- (NSError *)createAVAudioRecorder {

NSError *recorderSetupError = nil;

 [audioRecorder release];
audioRecorder = nil;

 NSString *timestamp = [NSString stringWithFormat:@"%d", (long)[[NSDate date] timeIntervalSince1970]];

 NSString *destinationString = [[MyAppDelegate getAppDocumentsDirectory] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.caf", timestamp]];
 NSLog(@"destinationString: %@", destinationString);
 NSURL *destinationUrl       = [NSURL fileURLWithPath: destinationString];

 audioRecorder = [[AVAudioRecorder alloc] initWithURL:destinationUrl 
                                          settings:[[AVRecordSettings sharedInstance] getSettings] 
                                             error:&recorderSetupError];

if (recorderSetupError) {

   UIAlertView *cantRecordAlert =
    [[UIAlertView alloc] initWithTitle:@"Can't record"
                           message:[recorderSetupError localizedDescription]
                          delegate:nil
                 cancelButtonTitle:@"OK"
                 otherButtonTitles:nil];
    [cantRecordAlert show];
    [cantRecordAlert release];
    return recorderSetupError;
} else {
  NSLog(@"no av setup error");
}

if ([audioRecorder prepareToRecord]) {
  recordPauseButton.enabled = YES;
  audioRecorder.delegate    = self;
 } else {
  NSLog(@"couldn't prepare to record");
 }

 NSLog (@"recorderSetupError: %@", recorderSetupError);

 return recorderSetupError;
 }
¿Fue útil?

Solución

Está fallando porque no inicializó el objeto AVAudioRecorder con la configuración adecuada. Haga esto antes de inicializarlo:

    NSDictionary *recordSettings =
    [[NSDictionary alloc] initWithObjectsAndKeys:
     [NSNumber numberWithFloat: 44100.0],                 AVSampleRateKey,
     [NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey,
     [NSNumber numberWithInt: 1],                         AVNumberOfChannelsKey,
     [NSNumber numberWithInt: AVAudioQualityMax],         AVEncoderAudioQualityKey,
     nil];

entonces puedes instanciarlo usando

audioRecorder = [[AVAudioRecorder alloc] initWithURL:destinationUrl 
                                          settings:recordSettings
                                             error:&recorderSetupError];

Otros consejos

El prepareToRecord también falla (silenciosamente, sin un error) si el directorio donde intenta guardar el archivo no existe. Use NSFileManager para verificar si el directorio ya existe.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top