objective-c – ios8 AVAudioEngine:播放多个(长)音频文件的正确方法

我试图在iOS 8中使用AVAudioEngine同步播放几个相当长的文件.

我可以用以下方法做到这一点:

- (void)startAudio {

    AVAudioMixerNode *mainMixer = [self.engine mainMixerNode];

    AVAudioPlayerNode *player = [[AVAudioPlayerNode alloc] init];
    AVAudioPlayerNode *player2 = [[AVAudioPlayerNode alloc] init];
    AVAudioPlayerNode *player3 = [[AVAudioPlayerNode alloc] init];

    [self.engine attachNode:player];
    [self.engine attachNode:player2];
    [self.engine attachNode:player3];

    NSString *fileName = [NSString stringWithFormat:@"%@/%@", [[NSBundle mainBundle] bundlePath], @"file1.caf"];
    NSURL *fileUrl = [NSURL fileURLWithPath:fileName];
    AVAudioFile *file = [[AVAudioFile alloc] initForReading:fileUrl error:nil];

    NSString *fileName2 = [NSString stringWithFormat:@"%@/%@", [[NSBundle mainBundle] bundlePath], @"file2.caf"];
    NSURL *fileUrl2 = [NSURL fileURLWithPath:fileName2];
    AVAudioFile *file2 = [[AVAudioFile alloc] initForReading:fileUrl2 error:nil];

    NSString *fileName3 = [NSString stringWithFormat:@"%@/%@", [[NSBundle mainBundle] bundlePath], @"file3.caf"];
    NSURL *fileUrl3 = [NSURL fileURLWithPath:fileName3];
    AVAudioFile *file3 = [[AVAudioFile alloc] initForReading:fileUrl3 error:nil];

    [self.engine connect:player to:mainMixer format:file.processingFormat];
    [self.engine connect:player2 to:mainMixer format:file2.processingFormat];
    [self.engine connect:player3 to:mainMixer format:file3.processingFormat];

    [player scheduleFile:file atTime:nil completionHandler:nil];
    [player2 scheduleFile:file2 atTime:nil completionHandler:nil];
    [player3 scheduleFile:file3 atTime:nil completionHandler:nil];

    NSError *error;
    [self.engine startAndReturnError:&error];
    [player play];
    [player2 play];
    [player3 play];
}

但这似乎很麻烦.我认为有一种方法可以将节点链接在一起,但我找不到任何示例,并且不清楚如何通过观看AVAudioEngine上的WWDC会话来做到这一点.

有任何想法吗?

最佳答案 你不应该atTime:nil,但是在不久的将来选择一个时间.比如现在0.1秒,并安排所有球员在那时进行比赛.

看看我的问题答案:Scheduling an audio file for playback in the future with AVAudioTime
找出方法.
scheduleSegment或scheduleFile以相同的方式工作,但是使用scheduleSegment,您可以在文件中的任何位置开始播放.

点赞