2016-07-12 25 views
3

我試圖使用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

回答