我尝试将多段音频合并为一个同步声音然后播放。我可以合并和播放,但我的应用程序的内存使用量会不断增加。
在线查看,AVPlayer似乎存在ARC /内存问题。
我已添加以下所有相关代码,用于设置文件,合并然后播放它们。
设置声音文件
- (void) setUpSoundFiles {
AVURLAsset *songAsset = nil;
AVAssetTrack *sourceAudioTrack = nil;
for (int i = 0; i < numberOfSoundsToMerge; i++){
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:[@(i) stringValue] ofType:@"mp3"]];
songAsset = [AVURLAsset URLAssetWithURL:url options:nil];
sourceAudioTrack = [[songAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0];
[songTracks insertObject:sourceAudioTrack atIndex:i];
[songAssets insertObject:[AVURLAsset URLAssetWithURL:url options:nil] atIndex:i];
//[sourceAudioTrack.asset cancelLoading];
}
}
合并声音文件
- (void) mergeAudio: (AVMutableComposition *)composition{
for(int i = 0; i < numberOfSoundsToMerge; i++) {
AVMutableCompositionTrack *track = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
NSError *error = nil;
BOOL ok = NO;
CMTime startTime = CMTimeMakeWithSeconds(0, 1);
CMTime trackDuration = ((AVURLAsset *)[songAssets objectAtIndex:i]).duration;
CMTimeRange tRange = CMTimeRangeMake(startTime, trackDuration);
//Set Volume
AVMutableAudioMixInputParameters *trackMix = [AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:track];
[trackMix setVolume:0.8f atTime:startTime];
[audioMixParams addObject:trackMix];
//Insert audio into track
ok = [track insertTimeRange:tRange ofTrack:(AVAssetTrack *)[songTracks objectAtIndex:i] atTime:CMTimeMake(0, 1) error:&error];
[((AVAssetTrack *)[songTracks objectAtIndex:i]).asset cancelLoading];
}
}
播放声音文件
- (void) playSounds {
AVMutableComposition *composition = [AVMutableComposition composition];
audioMixParams = [[NSMutableArray alloc] initWithObjects:nil];
[self mergeAudio:composition];
AVMutableAudioMix *audioMix = [AVMutableAudioMix audioMix];
audioMix.inputParameters = [NSArray arrayWithArray:audioMixParams];
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:composition];
AVPlayer *player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
[playerItem setAudioMix:audioMix];
[player play]; }