AVAudioFile无法在AVAudioEngine中播放

问题描述:

我试图使用AVAudioEngine播放AVAudioFile。代码很大程度上取自Apple Developer在线视频,但没有播放。已经花了一些时间去讨论论坛,但似乎没有任何亮点。AVAudioFile无法在AVAudioEngine中播放

我有两种方法。第一个调用标准的打开文件对话框,打开音频文件,分配一个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。

+0

只注意到我已经离开在playSoundFileAudioData方法(一个多余的行开始的两行的一个“引擎连接:”不过,。删除其中的任何一个都不能解决问题 – aseago

声明你AVAudioPlayerNode *player全球

参考此链接Can't play file from documents in AVAudioPlayer

+0

非常感谢Rahul--已经解决了这个问题! – aseago

+0

接受答案会很好 –

+0

对不起,Rahul。复选框没有出于我的iPad出于某种原因完成 – aseago