短影音時代,幾乎所有內容平台的首選畫幅都是正方形。但 AVFoundation 預設交給你的是裝置原生解析度(iPhone 6 為 1080×1920 的直式影片)。本文示範如何在不犧牲錄製品質的前提下,輸出一段從正中央裁切的正方形影片。
在前兩篇文章裡,我們用 AVCaptureSession 完成畫面擷取,再用 AVMutableComposition 把多段影音軌拼接起來。那兩個範例都是全螢幕錄影,難免只能拿到直式結果。
想改成正方形,不必在擷取階段就限制畫面,分成三層處理即可:
AVCaptureVideoPreviewLayer 設為正方形(寬高都取螢幕寬度),並垂直置中。AVMutableVideoComposition 從畫面正中央裁出正方形區域。
import UIKit
import AVFoundation
import Photos
import AVKit
class ViewController: UIViewController, AVCaptureFileOutputRecordingDelegate {
// 影片擷取工作階段,負責協調 input 到 output 的資料流
let captureSession = AVCaptureSession()
// 影像輸入裝置
let videoDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
// 音訊輸入裝置
let audioDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeAudio)
// 將擷取結果輸出成檔案
let fileOutput = AVCaptureMovieFileOutput()
var recordButton, saveButton: UIButton!
// 片段資源與路徑
var videoAssets = [AVAsset]()
var assetURLs = [String]()
var appendix: Int32 = 1
// 允許的總錄製秒數、每秒影格數
let totalSeconds: Float64 = 15.00
var framesPerSecond: Int32 = 30
var remainingTime: NSTimeInterval = 15.0
var stopRecording = false
var timer: NSTimer?
var progressBarTimer: NSTimer?
var incInterval: NSTimeInterval = 0.05
var progressBar = UIView()
var oldX: CGFloat = 0
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.blackColor()
// 註冊影像與音訊輸入
let videoInput = try! AVCaptureDeviceInput(device: self.videoDevice)
self.captureSession.addInput(videoInput)
let audioInput = try! AVCaptureDeviceInput(device: self.audioDevice)
self.captureSession.addInput(audioInput)
// 設定單段錄製上限並掛上輸出
let maxDuration = CMTimeMakeWithSeconds(totalSeconds, framesPerSecond)
self.fileOutput.maxRecordedDuration = maxDuration
self.captureSession.addOutput(self.fileOutput)
// 關鍵:預覽層設為正方形並垂直置中
let videoLayer = AVCaptureVideoPreviewLayer(session: self.captureSession)
videoLayer.frame = CGRectMake(0, self.view.bounds.height / 4,
self.view.bounds.width, self.view.bounds.width)
videoLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
self.view.layer.addSublayer(videoLayer)
self.setupButton()
self.captureSession.startRunning()
progressBar.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width,
height: self.view.bounds.height * 0.1)
progressBar.backgroundColor = UIColor(red: 4, green: 3, blue: 3, alpha: 0.5)
self.view.addSubview(progressBar)
}
func setupButton() {
self.recordButton = UIButton(frame: CGRectMake(0, 0, 120, 50))
self.recordButton.backgroundColor = UIColor.redColor()
self.recordButton.layer.masksToBounds = true
self.recordButton.setTitle("按住錄像", forState: .Normal)
self.recordButton.layer.cornerRadius = 20.0
self.recordButton.layer.position = CGPoint(x: self.view.bounds.width / 2,
y: self.view.bounds.height - 50)
self.recordButton.addTarget(self, action: #selector(onTouchDownRecordButton(_:)),
forControlEvents: .TouchDown)
self.recordButton.addTarget(self, action: #selector(onTouchUpRecordButton(_:)),
forControlEvents: .TouchUpInside)
self.saveButton = UIButton(frame: CGRectMake(0, 0, 70, 50))
self.saveButton.backgroundColor = UIColor.grayColor()
self.saveButton.layer.masksToBounds = true
self.saveButton.setTitle("保存", forState: .Normal)
self.saveButton.layer.cornerRadius = 20.0
self.saveButton.layer.position = CGPoint(x: self.view.bounds.width - 60,
y: self.view.bounds.height - 50)
self.saveButton.addTarget(self, action: #selector(onClickStopButton(_:)),
forControlEvents: .TouchUpInside)
self.view.addSubview(self.recordButton)
self.view.addSubview(self.saveButton)
}
// 按下開始錄製,寫入帶序號的暫存檔
func onTouchDownRecordButton(sender: UIButton) {
if !stopRecording {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsDirectory = paths[0] as String
let outputFilePath = "\(documentsDirectory)/output-\(appendix).mov"
appendix += 1
let outputURL = NSURL(fileURLWithPath: outputFilePath)
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(outputFilePath) {
do { try fileManager.removeItemAtPath(outputFilePath) } catch _ {}
}
fileOutput.startRecordingToOutputFileURL(outputURL, recordingDelegate: self)
}
}
// 放手結束本段錄製
func onTouchUpRecordButton(sender: UIButton) {
if !stopRecording {
timer?.invalidate()
progressBarTimer?.invalidate()
fileOutput.stopRecording()
}
}
func captureOutput(captureOutput: AVCaptureFileOutput!,
didStartRecordingToOutputFileAtURL fileURL: NSURL!,
fromConnections connections: [AnyObject]!) {
startProgressBarTimer()
startTimer()
}
func captureOutput(captureOutput: AVCaptureFileOutput!,
didFinishRecordingToOutputFileAtURL outputFileURL: NSURL!,
fromConnections connections: [AnyObject]!, error: NSError!) {
let asset = AVURLAsset(URL: outputFileURL, options: nil)
let duration = CMTimeGetSeconds(asset.duration)
videoAssets.append(asset)
assetURLs.append(outputFileURL.path!)
remainingTime = remainingTime - duration
// 時間用盡自動合併
if remainingTime <= 0 { mergeVideos() }
}
func startTimer() {
timer = NSTimer(timeInterval: remainingTime, target: self,
selector: #selector(ViewController.timeout), userInfo: nil, repeats: true)
NSRunLoop.currentRunLoop().addTimer(timer!, forMode: NSDefaultRunLoopMode)
}
func timeout() {
stopRecording = true
fileOutput.stopRecording()
timer?.invalidate()
progressBarTimer?.invalidate()
}
func startProgressBarTimer() {
progressBarTimer = NSTimer(timeInterval: incInterval, target: self,
selector: #selector(ViewController.progress),
userInfo: nil, repeats: true)
NSRunLoop.currentRunLoop().addTimer(progressBarTimer!, forMode: NSDefaultRunLoopMode)
}
func progress() {
let progressProportion = CGFloat(incInterval / totalSeconds)
let progressInc = UIView()
progressInc.backgroundColor = UIColor(red: 55/255, green: 186/255, blue: 89/255, alpha: 1)
let newWidth = progressBar.frame.width * progressProportion
progressInc.frame = CGRect(x: oldX, y: 0, width: newWidth, height: progressBar.frame.height)
oldX = oldX + newWidth
progressBar.addSubview(progressInc)
}
func onClickStopButton(sender: UIButton) { mergeVideos() }
// 合併片段並裁切為正方形
func mergeVideos() {
let duration = totalSeconds
let composition = AVMutableComposition()
let firstTrack = composition.addMutableTrackWithMediaType(
AVMediaTypeVideo, preferredTrackID: CMPersistentTrackID())
let audioTrack = composition.addMutableTrackWithMediaType(
AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID())
var insertTime: CMTime = kCMTimeZero
for asset in videoAssets {
do {
try firstTrack.insertTimeRange(
CMTimeRangeMake(kCMTimeZero, asset.duration),
ofTrack: asset.tracksWithMediaType(AVMediaTypeVideo)[0],
atTime: insertTime)
} catch _ {}
do {
try audioTrack.insertTimeRange(
CMTimeRangeMake(kCMTimeZero, asset.duration),
ofTrack: asset.tracksWithMediaType(AVMediaTypeAudio)[0],
atTime: insertTime)
} catch _ {}
insertTime = CMTimeAdd(insertTime, asset.duration)
}
// 旋轉 90 度,避免畫面上下顛倒
firstTrack.preferredTransform = CGAffineTransformMakeRotation(CGFloat(M_PI_2))
// 以短邊為基準決定最終渲染尺寸
print("視頻原始尺寸:", firstTrack.naturalSize)
let renderSize = CGSizeMake(firstTrack.naturalSize.height, firstTrack.naturalSize.height)
print("最終渲染尺寸:", renderSize)
let videoComposition = AVMutableVideoComposition()
videoComposition.frameDuration = CMTimeMake(1, framesPerSecond)
videoComposition.renderSize = renderSize
let instruction = AVMutableVideoCompositionInstruction()
instruction.timeRange = CMTimeRangeMake(
kCMTimeZero, CMTimeMakeWithSeconds(Float64(duration), framesPerSecond))
let transformer = AVMutableVideoCompositionLayerInstruction(assetTrack: firstTrack)
let t1 = CGAffineTransformMakeTranslation(
firstTrack.naturalSize.height,
-(firstTrack.naturalSize.width - firstTrack.naturalSize.height) / 2)
let t2 = CGAffineTransformRotate(t1, CGFloat(M_PI_2))
transformer.setTransform(t2, atTime: kCMTimeZero)
instruction.layerInstructions = [transformer]
videoComposition.instructions = [instruction]
let documentsPath = NSSearchPathForDirectoriesInDomains(
.DocumentDirectory, .UserDomainMask, true)[0]
let destinationPath = documentsPath + "/mergeVideo-\(arc4random() % 1000).mov"
let videoPath = NSURL(fileURLWithPath: destinationPath as String)
let exporter = AVAssetExportSession(asset: composition,
presetName: AVAssetExportPresetHighestQuality)!
exporter.outputURL = videoPath
exporter.outputFileType = AVFileTypeQuickTimeMovie
exporter.videoComposition = videoComposition
exporter.shouldOptimizeForNetworkUse = true
exporter.timeRange = CMTimeRangeMake(
kCMTimeZero, CMTimeMakeWithSeconds(Float64(duration), framesPerSecond))
exporter.exportAsynchronouslyWithCompletionHandler({
self.exportDidFinish(exporter)
})
}
func exportDidFinish(session: AVAssetExportSession) {
let outputURL = session.outputURL!
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideoAtFileURL(outputURL)
}, completionHandler: { (isSuccess: Bool, error: NSError?) in
dispatch_async(dispatch_get_main_queue(), {
self.reset()
let alertController = UIAlertController(title: "視頻保存成功",
message: "是否需要回看錄像?", preferredStyle: .Alert)
let okAction = UIAlertAction(title: "確定", style: .Default, handler: { _ in
self.reviewRecord(outputURL)
})
let cancelAction = UIAlertAction(title: "取消", style: .Cancel, handler: nil)
alertController.addAction(okAction)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
})
})
}
// 清理暫存檔與計時狀態,準備下一次錄製
func reset() {
for assetURL in assetURLs {
if NSFileManager.defaultManager().fileExistsAtPath(assetURL) {
do { try NSFileManager.defaultManager().removeItemAtPath(assetURL) } catch _ {}
}
}
for subview in progressBar.subviews { subview.removeFromSuperview() }
videoAssets.removeAll(keepCapacity: false)
assetURLs.removeAll(keepCapacity: false)
appendix = 1
oldX = 0
stopRecording = false
remainingTime = totalSeconds
}
func reviewRecord(outputURL: NSURL) {
let player = AVPlayer(URL: outputURL)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.presentViewController(playerViewController, animated: true) {
playerViewController.player!.play()
}
}
}
videoGravity 設為 ResizeAspectFill 是刻意的:它會填滿正方形區域並裁掉多餘部分,正好對應我們後製時的裁切邏輯;若改用 ResizeAspect,預覽會出現黑邊,與最終成品不一致。
裁切的重點在 t1 這個位移矩陣:先依旋轉後的座標系把畫面推回原點,再旋轉 90 度,最後水平方向扣掉「寬減高」的一半,就能取得正中間的正方形。實務上建議把這段封裝成獨立方法,日後要改 16:9 或 4:3 只需替換 renderSize 與位移計算。