如何在合并音频和视频时循环播放音频

Posted

技术标签:

【中文标题】如何在合并音频和视频时循环播放音频【英文标题】:How to loop audio while merging audio and video 【发布时间】:2017-01-14 06:06:39 【问题描述】:

我正在按照此代码合并音频和视频文件。它工作得很好。假设音频长度为 5 秒,视频长度为 20 秒。当我将这些文件合并到导出的视频中时,5 秒后没有声音。这很明显,因为我的音频长度是 5 秒。但是是否可以在整个视频会话中循环播放音频。

var finalVideoURL = NSURL()
var finalVideoName = String()

func mergeAudio&VideoFiles(videoUrl:NSURL, audioUrl:NSURL)
    let mixComposition : AVMutableComposition = AVMutableComposition()
    var mutableCompositionVideoTrack : [AVMutableCompositionTrack] = []
    var mutableCompositionAudioTrack : [AVMutableCompositionTrack] = []
    let totalVideoCompositionInstruction : AVMutableVideoCompositionInstruction = AVMutableVideoCompositionInstruction()
    //start merge
    let aVideoAsset : AVAsset = AVAsset(url: videoUrl as URL)
    let aAudioAsset : AVAsset = AVAsset(url: audioUrl as URL)
    mutableCompositionVideoTrack.append(mixComposition.addMutableTrack(withMediaType: AVMediaTypeVideo, preferredTrackID: kCMPersistentTrackID_Invalid))
    mutableCompositionAudioTrack.append( mixComposition.addMutableTrack(withMediaType: AVMediaTypeAudio, preferredTrackID: kCMPersistentTrackID_Invalid))
    let aVideoAssetTrack : AVAssetTrack = aVideoAsset.tracks(withMediaType: AVMediaTypeVideo)[0]
    let aAudioAssetTrack : AVAssetTrack = aAudioAsset.tracks(withMediaType: AVMediaTypeAudio)[0]
    do
        try mutableCompositionVideoTrack[0].insertTimeRange(CMTimeRangeMake(kCMTimeZero, aVideoAssetTrack.timeRange.duration), of: aVideoAssetTrack, at: kCMTimeZero)
        try mutableCompositionAudioTrack[0].insertTimeRange(CMTimeRangeMake(kCMTimeZero, aVideoAssetTrack.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)
    finalVideoURL = NSURL(fileURLWithPath: NSHomeDirectory() + "/Documents/FinalVideo.mp4")
    finalVideoName = "FinalVideo.mp4"
    let assetExport: AVAssetExportSession = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetHighestQuality)!
    assetExport.outputFileType = AVFileTypeMPEG4
    assetExport.outputURL = finalVideoURL as URL
    assetExport.shouldOptimizeForNetworkUse = true
    assetExport.exportAsynchronously  () -> Void in
        switch assetExport.status 
        case AVAssetExportSessionStatus.completed:
            print("Export movie to document directory from trimmed audio and mutable video complete :)")
        case  AVAssetExportSessionStatus.failed:
            print("failed \(assetExport.error)")
        case AVAssetExportSessionStatus.cancelled:
            print("cancelled \(assetExport.error)")
        default:
            print("complete")
        
    

【问题讨论】:

找到答案了吗? 没有。我是手动完成的。我不得不多次连接我的音频以获得相同长度的视频。然后我将视频文件与连接的音频文件合并(AVAssetExport)。 @pigeon_39你能通过代码告诉我,你是如何手动操作的。我也面临同样的问题。 【参考方案1】:

很久以前就有人问过,但它肯定可以帮助将来的人, 您可以通过多次插入 AVAssetTrack 的时间范围来做到这一点:

let vDuration = aVideoAsset.duration
let audioAssetTrack = mixComposition.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid)
do 
    var currentDuration = CMTime.zero
    while currentDuration < vDuration 
        let restTime = CMTimeSubtract(vDuration, currentDuration)
        let maxTime = CMTimeMinimum(aAudioAsset.duration, restTime)
        try audioAssetTrack.insertTimeRange(CMTimeRangeMake(start: CMTime.zero, duration: maxTime),
                                          of: aAudioAsset.tracks(withMediaType: .audio)[0],
                                          at: currentDuration)
        currentDuration = CMTimeAdd(currentDuration, aAudioAsset.duration)
    
 catch 
     print("Failed to load audio track")
     continue

     

【讨论】:

以上是关于如何在合并音频和视频时循环播放音频的主要内容,如果未能解决你的问题,请参考以下文章

js中怎么让音频重复播放

如何使用jQuery无限循环播放音频文件

如果背景音频处于活动状态,MPMoviePlayerController 将冻结

iOS音频播放录音视频播放拍照视频录制

计算循环次数并停止播放音频

AVFoundation 如何循环播放一段特定时间的音频?