2016-12-20 159 views
2

我有five.caf我想同时播放多个文件的文件(不同的音乐家的声音)。为此,我使用了AVAudioPlayer类。我创建了AVAudioPlayer的五个实例并设置了网址并播放歌曲。但它没有正确同步。看起来像一两​​个音乐家的声音延迟到一秒钟。 如何在同一时间同步所有歌曲并播放它们。同时播放多首歌曲

下面是我的代码:

// 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 

回答

0

做一个并发调度队列和调度队列

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]; 
}); 

希望这有助于的并行分支播放的文件。

+0

感谢您的宝贵意见。我已经尝试过您的解决方案,但仍然像以前一样延迟了声音。 –

相关问题