我正在制作一个简单的视频编辑应用。我想为我的应用添加慢动作。我注意到AVMutableCompositionTrack类中有一个scaleTimeRange方法,所以我用它来实现我的目的。我发现scaleTimeRange在视频轨道上运行良好,但对音轨没有任何影响。这意味着音轨仍以原始速度播放。
关注我的代码:
CMTime insertionPoint = kCMTimeZero;
double wholeDuration = CMTimeGetSeconds([asset duration]);
double doubleDuration = CMTimeGetSeconds([asset duration])*2.0;
CMTime trimmedDuration = CMTimeMakeWithSeconds(wholeDuration, 600.0);
// Create a new composition
self.mutableComposition = [AVMutableComposition composition];
// Insert video and audio tracks from AVAsset
if(assetVideoTrack != nil) {
AVMutableCompositionTrack *compositionVideoTrack = [self.mutableComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
[compositionVideoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, trimmedDuration) ofTrack:assetVideoTrack atTime:insertionPoint error:&error];
[compositionVideoTrack scaleTimeRange:CMTimeRangeMake(kCMTimeZero, trimmedDuration) toDuration:CMTimeMakeWithSeconds(doubleDuration, 600.0)];
}
if(assetAudioTrack != nil) {
AVMutableCompositionTrack *compositionAudioTrack = [self.mutableComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
[compositionAudioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, trimmedDuration) ofTrack:assetAudioTrack atTime:insertionPoint error:&error];
[compositionAudioTrack scaleTimeRange:CMTimeRangeMake(kCMTimeZero, trimmedDuration) toDuration:CMTimeMakeWithSeconds(doubleDuration, 600.0)];
}
有人能就这个问题给我一些建议吗?谢谢!
答案 0 :(得分:5)
为了能够播放带有声音的慢动作,只需为AVPlayerItem设置合适的audioTimePitchAlgorithm
playerItem.audioTimePitchAlgorithm = AVAudioTimePitchAlgorithmVarispeed;
答案 1 :(得分:1)
由于apple api中的错误,ScaleTimeRange不适用于音频(错误号:14616144)。但是,可以使用重新采样来完成时间缩放音频。如果以48 kHz采样音频,重新采样至96 kHz并以48 kHz播放音频,则播放时间将延长两倍。一般为:
scaledSampleRate = (orignalSampleRate / playRate);
playRate = (originalSampleRate / scaledSampleRate);
如果不希望,音高会降低。解决方案可能是第三方API。如果您可以将音频提取到单独的播放器,我猜您可以使用AVAudioPlayer,您可以在其中设置播放速率:
player = [[AVAudioPlayer alloc] initWithContentsOfURL:
[NSURL fileURLWithPath:path] error:&err];
player.volume = 0.4f;
player.enableRate=YES;
[player prepareToPlay];
[player setNumberOfLoops:0];
player.rate=2.0f;
[player play];
答案 2 :(得分:0)
如果您正在使用scaleTimeRange,并且想知道为什么它不起作用或播放任何音频,那么您应该将其添加到playerItem。
playerItem.audioTimePitchAlgorithm = AVAudioTimePitchAlgorithm.varispeed