适用于 iOS 的 Xcode
我遇到的问题是播放 AVMutableComposition。我正在创建组合,然后在 for 循环中将 AVURLAssets 添加到它。我正在添加所有内容,就像我将类似地将对象添加到可变数组中一样,然后尝试在之后播放它,但没有播放。这是我的代码:
AVMutableComposition *composition = [AVMutableComposition composition];
int count;
count = array.count;
for (int y=0;y<count;y++){
NSURL *url;
url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@.mp3", [[NSBundle mainBundle] resourcePath],[array objectAtIndex:y]]];
NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
AVURLAsset *sourceAsset = [[AVURLAsset alloc] initWithURL:url options:options];
//calculate times
NSNumber *time = [soundArray1 objectAtIndex:1];
double timenow = [time doubleValue];
double insertTime = (240*y);
CMTime douTime = CMTimeMake(240, timenow);
CMTime staTime = CMTimeMake(0, 1);
CMTimeRange editRange = CMTimeRangeMake(staTime,douTime);
CMTime insTime = CMTimeMake(insertTime, timenow);
NSError *editError;
[composition insertTimeRange:editRange ofAsset:sourceAsset atTime:insTime error:&editError];
}
AVPlayer* mp = [AVPlayer playerWithPlayerItem:[AVPlayerItem playerItemWithAsset:composition]];
[mp play];
我假设我完全错了,但是我在循环中而不是之后添加了这个,在 if 中并打开一个 NSRunLoop 来检查(有点糟糕,但这只是为了测试!):
AVMutableComposition *composition = [AVMutableComposition composition];
int count;
count = array.count;
for (int y=0;y<count;y++){
NSURL *url;
url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@.mp3", [[NSBundle mainBundle] resourcePath],[array objectAtIndex:y]]];
NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
AVURLAsset *sourceAsset = [[AVURLAsset alloc] initWithURL:url options:options];
//calculate times
NSNumber *time = [soundArray1 objectAtIndex:1];
double timenow = [time doubleValue];
double insertTime = (240*y);
CMTime douTime = CMTimeMake(240, timenow);
CMTime staTime = CMTimeMake(0, 1);
CMTimeRange editRange = CMTimeRangeMake(staTime,douTime);
CMTime insTime = CMTimeMake(insertTime, timenow);
NSError *editError;
[composition insertTimeRange:editRange ofAsset:sourceAsset atTime:insTime error:&editError];
if(y==3){
AVPlayer* mp = [AVPlayer playerWithPlayerItem:[AVPlayerItem playerItemWithAsset:composition]];
[mp play];
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:20]];
}
}
在这里,我只是给了我的数组 4 个元素,并让它在第 4 次运行时播放合成。它工作并以完美的顺序播放了我的 4 个音频文件。
我需要做什么才能使我的作曲在这个循环之后而不是在循环中播放?我是否误用了系统?
编辑:通过将我打开的 RunLoop 代码粘贴到最后,它会播放。我应该这样做,还是有更好的方法来做到这一点?