Created
February 8, 2024 05:05
-
-
Save Anik0808/3bf8c786aa968de197a499516261d3ef to your computer and use it in GitHub Desktop.
This code writes series of pixel buffer to files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//generate a file url to store the video. some_image.jpg becomes some_image.mov | |
guard let outputMovieURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("output.mov") else { | |
fatalError("somehting went wrong") //an error i made up | |
} | |
//delete any old file | |
do { | |
try FileManager.default.removeItem(at: outputMovieURL) | |
} catch { | |
print("Could not remove file \(error.localizedDescription)") | |
} | |
//create an assetwriter instance | |
guard let assetwriter = try? AVAssetWriter(outputURL: outputMovieURL, fileType: .mov) else { | |
abort() | |
} | |
//generate 1080p settings | |
let settingsAssistant = AVOutputSettingsAssistant(preset: .preset1920x1080)?.videoSettings | |
//create a single video input | |
let assetWriterInput = AVAssetWriterInput(mediaType: .video, outputSettings: settingsAssistant) | |
//create an adaptor for the pixel buffer | |
let assetWriterAdaptor = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: assetWriterInput, sourcePixelBufferAttributes: nil) | |
//add the input to the asset writer | |
assetwriter.add(assetWriterInput) | |
//begin the session | |
assetwriter.startWriting() | |
assetwriter.startSession(atSourceTime: CMTime.zero) | |
//determine how many frames we need to generate | |
let framesPerSecond = 30 | |
//duration is the number of seconds for the final video | |
let totalFrames = 1 * framesPerSecond | |
var frameCount = 0 | |
//replace the while true condition to loop through the pixelbuffers | |
while true{ | |
if assetWriterInput.isReadyForMoreMediaData { | |
let frameTime = CMTimeMake(value: Int64(frameCount), timescale: Int32(framesPerSecond)) | |
//append the contents of the pixelBuffer at the correct time | |
assetWriterAdaptor.append(pixelBuffer, withPresentationTime: frameTime) | |
frameCount+=1 | |
print(frameCount) | |
} | |
} | |
//close everything | |
assetWriterInput.markAsFinished() | |
assetwriter.finishWriting { | |
print("writing complete ✅") | |
// pixelBuffer = nil | |
//outputMovieURL now has the video | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment