AVasset требует времени для загрузки (только для видеоформатов). Но простые форматы не требуют времени (объединены видео и аудио). Эта проблема была даже воспроизведена в AVPlayer (url: URL (строка: * URL, полученный с YouTube api / as! String)!) *
func mergeFilesWithUrl(videoUrl:URL, audioUrl:URL, completion: @escaping (Bool) -> (Void))
{
let mixComposition : AVMutableComposition = AVMutableComposition()
var mutableCompositionVideoTrack : [AVMutableCompositionTrack] = []
var mutableCompositionAudioTrack : [AVMutableCompositionTrack] = []
let totalVideoCompositionInstruction : AVMutableVideoCompositionInstruction = AVMutableVideoCompositionInstruction()
let aVideoAsset : AVAsset = AVAsset(url: videoUrl) //Here is the issue
let key = "playable"
DispatchQueue.main.async {
aVideoAsset.loadValuesAsynchronously(forKeys: [key], completionHandler: {
let status = aVideoAsset.statusOfValue(forKey: key, error: nil)
if status == AVKeyValueStatus.loaded {
let aAudioAsset : AVAsset = AVAsset(url: audioUrl)
aAudioAsset.loadValuesAsynchronously(forKeys: [key], completionHandler: {
let status1 = aAudioAsset.statusOfValue(forKey: key, error: nil)
if status1 == AVKeyValueStatus.loaded {
mutableCompositionVideoTrack.append(mixComposition.addMutableTrack(withMediaType: AVMediaType.video, preferredTrackID: kCMPersistentTrackID_Invalid)!)
mutableCompositionAudioTrack.append( mixComposition.addMutableTrack(withMediaType: AVMediaType.audio, preferredTrackID: kCMPersistentTrackID_Invalid)!)
let aVideoAssetTrack : AVAssetTrack = aVideoAsset.tracks(withMediaType: AVMediaType.video)[0]
let aAudioAssetTrack : AVAssetTrack = aAudioAsset.tracks(withMediaType: AVMediaType.audio)[0]
do{
try mutableCompositionVideoTrack[0].insertTimeRange(CMTimeRangeMake(kCMTimeZero, aVideoAssetTrack.timeRange.duration), of: aVideoAssetTrack, at: kCMTimeZero)
try mutableCompositionAudioTrack[0].insertTimeRange(CMTimeRangeMake(kCMTimeZero, aAudioAssetTrack.timeRange.duration), of: aAudioAssetTrack, at: kCMTimeZero)
} catch{
}
totalVideoCompositionInstruction.timeRange = CMTimeRangeMake(kCMTimeZero,aVideoAssetTrack.timeRange.duration )
let mutableVideoComposition : AVMutableVideoComposition = AVMutableVideoComposition()
mutableVideoComposition.frameDuration = CMTimeMake(1, 30)
mutableVideoComposition.renderSize = CGSize(width: 1280,height: 720)
self.mixComposition = mixComposition
_ = completion(true)
}
})
}
})
}
}