Ios 同时播放多首歌曲

Ios 同时播放多首歌曲,ios,avaudioplayer,Ios,Avaudioplayer,我有5个.caf文件(具有不同的音乐家声音),我希望与多个文件同时播放。为此,我使用了AVAudioPlayer类。我已经创建了五个AVAudioPlayer实例,设置了url并播放了歌曲。但它不能正确同步。看起来一两个音乐家的声音延迟到了一秒钟如何同时同步所有歌曲并播放它们。 以下是我的代码: // Song1 NSString *FilePath = [NSString stringWithFormat:@"%@/songs/%@", [[GlobalClass sharedInstance

我有
5个.caf
文件(具有不同的音乐家声音),我希望与多个文件同时播放。为此,我使用了
AVAudioPlayer
类。我已经创建了五个
AVAudioPlayer
实例,设置了url并播放了歌曲。但它不能正确同步。看起来一两个音乐家的声音延迟到了一秒钟如何同时同步所有歌曲并播放它们。

以下是我的代码:

// Song1
NSString *FilePath = [NSString stringWithFormat:@"%@/songs/%@", [[GlobalClass sharedInstance] GetDocPath], SongFileName];
NSString *url = [FilePath stringByAppendingString:@"/Song1.caf"];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:url] error:nil];
[player setDelegate:self];
[player prepareToPlay];
player.numberOfLoops = 0;

// Song2
NSString *url1 = [FilePath stringByAppendingString:@"/Song2.caf"];
player1 = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:url1] error:nil];
[player1 setDelegate:self];
[player1 prepareToPlay];
player1.numberOfLoops = 0;

// Song3
NSString *url2 = [FilePath stringByAppendingString:@"/Song3.caf"];
player2 = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:url2] error:nil];
[player2 setDelegate:self];
[player2 prepareToPlay];
player2.numberOfLoops = 0;

// Song4
NSString *url3 = [FilePath stringByAppendingString:@"/Song4.caf"]; // ALT.caf
player3 = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:url3] error:nil];
[player3 setDelegate:self];
[player3 prepareToPlay];
player3.numberOfLoops = 0;
NSLog(@"player3: %f", player3.duration);

// Song5
NSString *url4 = [FilePath stringByAppendingString:@"/Song5.caf"]; 
player4 = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:url4] error:nil];
[player4 setDelegate:self];
[player4 prepareToPlay];
player4.numberOfLoops = 0;

[player play]; // Band
[player1 play]; // Song1
[player2 play]; // Song2
[player3 play]; // Song3
[player4 play]; // Song4

创建并发调度队列并播放调度队列并发分支中的文件

dispatch_queue_t parallelQueue = dispatch_queue_create("com.unique.name.queue", DISPATCH_QUEUE_CONCURRENT);

dispatch_async(parallelQueue, ^{
    [player play];
});
dispatch_async(parallelQueue, ^{
    [player1 play];
});
dispatch_async(parallelQueue, ^{
     [player2 play];
});
dispatch_async(parallelQueue, ^{
     [player3 play];
});
dispatch_async(parallelQueue, ^{
     [player4 play];
});

希望这能有所帮助。

谢谢你的宝贵建议。我已经尝试过你的解决方案,但仍然像以前一样延迟声音。