Ios:从视频中删除音频

时间:2015-10-13 10:27:00

标签: ios iphone audio video

我有时需要静音视频发送最终用户,所以我需要从视频中删除音频文件。 传递单个进程的视频静音。

1 个答案:

答案 0 :(得分:0)

在Swift 3中,

func removeAudioFromVideo(_ videoPath: String) {
    let initPath1: String = videoPath
    let composition = AVMutableComposition()
    let inputVideoPath: String = initPath1
    let sourceAsset = AVURLAsset(url: URL(fileURLWithPath: inputVideoPath), options: nil)
    let compositionVideoTrack: AVMutableCompositionTrack? = composition.addMutableTrack(withMediaType: AVMediaTypeVideo, preferredTrackID: kCMPersistentTrackID_Invalid)
    let sourceVideoTrack: AVAssetTrack? = sourceAsset.tracks(withMediaType: AVMediaTypeVideo)[0]
    let x: CMTimeRange = CMTimeRangeMake(kCMTimeZero, sourceAsset.duration)
    _ = try? compositionVideoTrack!.insertTimeRange(x, of: sourceVideoTrack!, at: kCMTimeZero)
    if FileManager.default.fileExists(atPath: initPath1) {
        try? FileManager.default.removeItem(atPath: initPath1)
    }
    let url = URL(fileURLWithPath: initPath1)
    let exporter = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetHighestQuality)
    exporter?.outputURL = url
    exporter?.outputFileType = "com.apple.quicktime-movie"
    exporter?.exportAsynchronously(completionHandler: {() -> Void in
        self.saveFinalVideoFile(toDocuments: exporter!.outputURL!)
    })
}

func saveFinalVideoFile(toDocuments url: URL) {
    let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("Videos")
    let movieData = try? Data(contentsOf: url)
    try? movieData?.write(to: fileURL, options: .atomic)
}