我正在尝试合并 4 个音频文件并播放它们。以下是代码
- (BOOL) combineVoices {
NSMutableArray * arr=[[NSMutableArray alloc] init];
[arr addObject:@"player_4_full"];
[arr addObject:@"event_1_1_1"];
[arr addObject:@"team_2_1"];
[arr addObject:@"event_1_1_2"];
NSError *error = nil;
BOOL ok = NO;
CMTime nextClipStartTime = kCMTimeZero;
//Create AVMutableComposition Object.This object will hold our multiple AVMutableCompositionTrack.
AVMutableComposition *composition = [[AVMutableComposition alloc] init];
AVMutableCompositionTrack *compositionAudioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
for(NSString * str in arr)
{
NSString *path = [[NSBundle mainBundle] pathForResource:str ofType:@"mp3"];
NSURL *url = [[NSURL alloc] initFileURLWithPath:path];
AVAsset *avAsset = [[AVURLAsset alloc] initWithURL:url options:nil];
NSArray *tracks = [avAsset tracksWithMediaType:AVMediaTypeAudio];
if ([tracks count] == 0)
return NO;
NSLog(@"%@",avAsset);
CMTimeRange timeRangeInAsset = CMTimeRangeMake(kCMTimeZero, [avAsset duration]);
AVAssetTrack *clipAudioTrack = [[avAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0];
ok = [compositionAudioTrack insertTimeRange:timeRangeInAsset ofTrack:clipAudioTrack atTime:nextClipStartTime error:&error];
if (!ok) {
NSLog(@"Current Video Track Error: %@",error);
}
nextClipStartTime = CMTimeAdd(nextClipStartTime, timeRangeInAsset.duration);
}
NSLog(@"%@",composition);
self.item = [[AVPlayerItem alloc] initWithAsset:composition];
self.p =[AVPlayer playerWithPlayerItem:item];
[self.p play];
return YES;
}
问题是合并后我可以在模拟器中播放声音。但是当我在设备上播放时,我只能在耳机中听到声音,而不是在扬声器上