Сбой AVAudioPlayer после обновления до iOS 5.0

#iphone #objective-c #ipad #avaudioplayer #exc-bad-access

#iPhone #objective-c #iPad #avaudioplayer #исключение-bad-access

Вопрос:

Я успешно использовал класс AVAudioPlayer, но после обновления до iOS 5.0 мое приложение для iPad вылетает при попытке прослушать то, что я ранее записал. Под iOS 4.3 все хорошо.

Вот код:

    NSError * error = NULL;
   player =[[AVAudioPlayer alloc] initWithContentsOfURL: 
                             [NSURL fileURLWithPath:destinationString] 
                             error:amp;error]; 

   if(player == NULL)
    NSLog( @"error in creating AVAudioPlayer - %@ %@", [error domain], [error localizedDescription] );

         [player prepareToPlay];
         player.delegate = self;
         [player play]; 

- (NSString*) documentsPath
{
    NSArray *searchPaths =
    NSSearchPathForDirectoriesInDomains
    (NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* _documentsPath = [searchPaths objectAtIndex: 0];  
    return _documentsPath;
}

-(void) initRecord
{
    audioSession = [[AVAudioSession sharedInstance] retain];
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error: nil];
    [audioSession setActive:YES error:nil];

    destinationString = [[self documentsPath]
                         stringByAppendingPathComponent:@"myRecording.caf"];
    NSLog(@"%@", destinationString);
    NSURL *destinationURL = [NSURL fileURLWithPath: destinationString];

    NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
                              [NSNumber numberWithFloat: 44100.0],                 AVSampleRateKey,
                              [NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey,
                              [NSNumber numberWithInt: 1],                         AVNumberOfChannelsKey,
                              [NSNumber numberWithInt: AVAudioQualityMax],         AVEncoderAudioQualityKey,
                              nil];
    NSError *error;
    recorder = [[AVAudioRecorder alloc] initWithURL:destinationURL settings:settings error:amp;error];
    recorder.delegate = self;
}
  

Приложение завершает работу в этой строке:

  player =[[AVAudioPlayer alloc] initWithContentsOfURL: 
                             [NSURLfileURLWithPath:destinationString] 
                             error:NULL]; 
  

Я уже пробовал NSZombieEnabled, который дает мне:

 0x5368b0 <myRecording = 005BD7D0 | Tag = -1>
*** -[NSPathStore2 length]: message sent to deallocated instance 0x5290e0
  

Ответ №1:

измените эти начальные строки на:

 -(void) playRecording
{
    AVAudioPlayer * player = NULL;

    if(destinationString amp;amp; ([destinationString length] > 15)
    {
        NSError * error = NULL;
        player =[[AVAudioPlayer alloc] initWithContentsOfURL: 
                             [NSURL fileURLWithPath:destinationString] 
                             error:amp;error]; 

        if(player == NULL)
        {
            NSLog( @"error in creating AVAudioPlayer - %@ %@", [error domain], [error localizedDescription] );
        } else {
            [player prepareToPlay];
            player.delegate = self;
            [player play]; 
            // F.Y.I. -- this player NEEDS to be released when it is done playing
            // 
            // right now you appear to be leaking memory from both AVAudioPlayer and AVAudioRecorder
        }
    } else {
        NSLog( @"destination string doesn't exist or is invalid");
    }
}
  

Я также дал вам некоторый код проверки ошибок.

Комментарии:

1. Я протестирую его и сообщу вам о результатах. Спасибо за вашу помощь 🙂

2. Привет, Майкл. Теперь я получил эти две ошибки: ошибка при создании AVAudioPlayer — (null) (null) amp; -[длина NSPathStore2]: сообщение отправлено в освобожденный экземпляр 0x59b9340. Я не знаю почему, но после обновления до iOS 5 возникает эта ошибка при создании AVAudioPlayer.

3. Не могли бы вы обновить свой первоначальный вопрос новым кодом и позволить мне (или кому-либо еще) посмотреть, что происходит в контексте?

4. Конечно, я только что это сделал, а также поделился методом initRecord.

5. И я также обновил свой код. У меня сильное ощущение, что ваш автоматически выпущенный «destinationString» равен нулю.