我有 five.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];
});
希望这会有所帮助。
关于ios - 同时播放多首歌曲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41235312/
欢迎光临 OGeek|极客世界-中国程序员成长平台 (https://ogeek.cn/) | Powered by Discuz! X3.4 |