如何录制视频并使其慢动作

时间:2011-06-18 23:50:20

标签: iphone ios4 video-capture

我正在为学校开发iPhone应用程序并需要一些帮助。该应用程序应录制视频,使其慢动作(约2倍),然后将其保存到照片库。到目前为止,除了如何使视频慢动作外,我还有其他一切。我知道它可以完成,因为App Store中已有一个应用程序可以完成它。

如何将我保存的视频保存到临时网址并调整速度,然后再保存到照片库?

3 个答案:

答案 0 :(得分:3)

如果您需要导出视频,则需要使用AVMutableComposition Class

然后将您的视频AVAsset添加到AVMutableComposition并将其缩放为:

- (void)scaleTimeRange:(CMTimeRange)timeRange toDuration:(CMTime)duration

最后,您使用AVAssetExportSession Class

导出它

答案 1 :(得分:0)

我编写了一段代码,让您的视频以“慢动作”呈现,并将其保存在照片库中。 “此代码适用于 Swift 5 的主要内容”。在 iOS swift 中创建“慢动作”视频并不容易,我遇到了许多“慢动作”,后来发现它们不起作用或其中的一些代码已贬值。所以我终于找到了一种在 Swift 中制作慢动作的方法。 此代码可用于 120fps 大于此值。只需添加视频的网址并使其变慢

这是“我为实现慢动作而创建的代码片段”

如果此代码有效,请给我一个 UPVOTE。

        func slowMotion(pathUrl: URL) {

    let videoAsset = AVURLAsset.init(url: pathUrl, options: nil)
    let currentAsset = AVAsset.init(url: pathUrl)

    let vdoTrack = currentAsset.tracks(withMediaType: .video)[0]
    let mixComposition = AVMutableComposition()

    let compositionVideoTrack = mixComposition.addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid)

    let videoInsertError: Error? = nil
    var videoInsertResult = false
    do {
        try compositionVideoTrack?.insertTimeRange(
            CMTimeRangeMake(start: .zero, duration: videoAsset.duration),
            of: videoAsset.tracks(withMediaType: .video)[0],
            at: .zero)
        videoInsertResult = true
    } catch let videoInsertError {
    }

    if !videoInsertResult || videoInsertError != nil {
        //handle error
        return
    }


    var duration: CMTime = .zero
    duration = CMTimeAdd(duration, currentAsset.duration)
    
    
    //MARK: You see this constant (videoScaleFactor) this helps in achieving the slow motion that you wanted. This increases the time scale of the video that makes slow motion
    // just increase the videoScaleFactor value in order to play video in higher frames rates(more slowly)
    let videoScaleFactor = 2.0
    let videoDuration = videoAsset.duration
    
    compositionVideoTrack?.scaleTimeRange(
        CMTimeRangeMake(start: .zero, duration: videoDuration),
        toDuration: CMTimeMake(value: videoDuration.value * Int64(videoScaleFactor), timescale: videoDuration.timescale))
    compositionVideoTrack?.preferredTransform = vdoTrack.preferredTransform
    
    let dirPaths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).map(\.path)
    let docsDir = dirPaths[0]
    let outputFilePath = URL(fileURLWithPath: docsDir).appendingPathComponent("slowMotion\(UUID().uuidString).mp4").path
    
    if FileManager.default.fileExists(atPath: outputFilePath) {
        do {
            try FileManager.default.removeItem(atPath: outputFilePath)
        } catch {
        }
    }
    let filePath = URL(fileURLWithPath: outputFilePath)
    
    let assetExport = AVAssetExportSession(
        asset: mixComposition,
        presetName: AVAssetExportPresetHighestQuality)
    assetExport?.outputURL = filePath
    assetExport?.outputFileType = .mp4
    
    assetExport?.exportAsynchronously(completionHandler: {
        switch assetExport?.status {
        case .failed:
            print("asset output media url = \(String(describing: assetExport?.outputURL))")
            print("Export session faiied with error: \(String(describing: assetExport?.error))")
            DispatchQueue.main.async(execute: {
                // completion(nil);
            })
        case .completed:
            print("Successful")
            let outputURL = assetExport!.outputURL
            print("url path = \(String(describing: outputURL))")
            
            PHPhotoLibrary.shared().performChanges({
                PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: outputURL!)
            }) { saved, error in
                if saved {
                    print("video successfully saved in photos gallery view video in photos gallery")
                }
                if (error != nil) {
                    print("error in saing video \(String(describing: error?.localizedDescription))")
                }
            }
            DispatchQueue.main.async(execute: {
                //      completion(_filePath);
            })
        case .none:
            break
        case .unknown:
            break
        case .waiting:
            break
        case .exporting:
            break
        case .cancelled:
            break
        case .some(_):
            break
        }
    })
}

答案 2 :(得分:-1)

slowmoVideo是一个OSS项目,看起来非常好,虽然我不知道它可以在iPhone上运行。

  

它不会简单地让您的视频以0.01倍的速度播放。您可以   平稳地减速和加速你的镜头,可选择运动   模糊。慢动作如何工作? slowmoVideo试图找出在哪里   像素在视频中移动(此信息称为光流),   然后使用此信息计算其他帧。

相关问题