AVAudioFile не воспроизводится в AVAudioEngine

Я пытаюсь воспроизвести AVAudioFile с помощью AVAudioEngine. Код в основном взят и адаптирован из он-лайн видео от Apple Developer, но воспроизведения нет. Потратил некоторое время на просмотр форумов, но, кажется, ничто не проливает свет на это.

У меня есть два метода. Первый вызывает стандартный диалог открытия файла, открывает аудиофайл, выделяет объект AVAudioBuffer (который я буду использовать позже) и заполняет его аудиоданными. Второй настраивает объекты AVAudioEngine и AVAudioPlayerNode, соединяет все и воспроизводит файл. Два метода перечислены ниже.

- (IBAction)getSoundFileAudioData:(id)sender {


    NSOpenPanel* openPanel = [NSOpenPanel openPanel];

    openPanel.title = @"Choose a .caf file";
    openPanel.showsResizeIndicator = YES;
    openPanel.showsHiddenFiles = NO;
    openPanel.canChooseDirectories = NO;
    openPanel.canCreateDirectories = YES;
    openPanel.allowsMultipleSelection = NO;
    openPanel.allowedFileTypes = @[@"caf"];

    [openPanel beginWithCompletionHandler:^(NSInteger result){
       if (result == NSFileHandlingPanelOKButton) {
        NSURL*  theAudioFileURL = [[openPanel URLs] objectAtIndex:0];

        // Open  the document.

        theAudioFile = [[AVAudioFile alloc] initForReading:theAudioFileURL error:nil];

        AVAudioFormat *format = theAudioFile.processingFormat;
        AVAudioFrameCount capacity = (AVAudioFrameCount)theAudioFile.length;

        theAudioBuffer = [[AVAudioPCMBuffer alloc] 
             initWithPCMFormat:format frameCapacity:capacity];
        NSError *error;
        if (![theAudioFile readIntoBuffer:theAudioBuffer error:&error])  {

            NSLog(@"problem filling buffer");

        }
        else
            playOrigSoundFileButton.enabled = true;            

    }

}];}





- (IBAction)playSoundFileAudioData:(id)sender {



    AVAudioEngine *engine = [[AVAudioEngine alloc] init]; // set up the audio engine

    AVAudioPlayerNode *player = [[AVAudioPlayerNode alloc] init]; // set up a player node

    [engine attachNode:player]; // attach player node to engine

    AVAudioMixerNode *mixer = [engine mainMixerNode];
    [engine connect:player to:mixer format:theAudioFile.processingFormat]; // connect player node to mixer
    [engine connect:player to:mixer format:[mixer outputFormatForBus:0]]; // connect player node to mixer

    NSError *error;

    if (![engine startAndReturnError:&error]) {
        NSLog(@"Problem starting engine ");
    }
    else {

        [player scheduleFile:theAudioFile atTime: nil completionHandler:nil];
        [player play];
    }

}

Я проверил, что функции выполняются, что аудио движок работает и аудио файл прочитан. Я также пробовал с различными форматами аудио файлов, как моно, так и стерео. Есть идеи?

Я использую Xcode 7.3.1.

1 ответ

Решение

Объявить свой AVAudioPlayerNode *player как глобальный

обратитесь по этой ссылке Невозможно воспроизвести файл из документов в AVAudioPlayer

Другие вопросы по тегам