How to stream CMSampleBuffer to file in Swift?

I've been exploring the sample code from the ReplayKit sample code, here.

I'm essentially looking for a way to alter the below function to append the data from sampleBuffer to a file. I'm struggling to find relevant examples online or in the forums here. Any tips would be appreciated.

Code Block swift
func processAppAudioSample(sampleBuffer: CMSampleBuffer) {
        print("Received an audio sample.")
//Append sampleBuffer to file here
??
}


While this may not prove to be the most robust of answers, I believe this would be a use case for AVAssetWriter. Succinctly, you could hypothetically instantiate an AVAssetWriter instance before your ReplayKit session begins, then call startWriting() once your app calls the startCapture() method, per the sample app you linked to. Once stopCapture() is called in the app, you could stop the AVAssetWriter, which would then save the created file to a defined location.

Going to your question directly, the processAppAudioSample(sampleBuffer: CMSampleBuffer) method would be modified to append the sample buffer to the file being created, by way of the AVAssetWriter's input.

In short, you set up your AVAssetWriter, call startWriting() when your ReplayKit session begins, append each sample buffer to the AVAssetWriter's input, then mark the writing as finished once your ReplayKit session ends.

AVAssetWriter is available on iOS, macOS, tvOS, and through Mac Catalyst, and is a part of AVFoundation. Admittedly, AVAssetWriter can be a bit to wrap your head around at first (it has many, many configurable options as you're dealing with file formats, codecs, resolutions, bitrates, etc.), but there are plenty of great tutorials and sample code available online. It took me some time to grasp it, but for what you're after, you should find plenty of samples on how to just create a file by appending the sample buffers, and you can learn more about the configurable options as you need.

As an aside, if you're looking to record computer audio/microphone audio only, you don't need ReplayKit to be involved. I'm not sure of your use case, so ReplayKit may be relevant, but AVFoundation provides tools to capture audio from a built-in/external microphone, or computer audio, without using ReplayKit (ReplayKit does, however, provide a great interface for users and considers user privacy, so it should not be discredited).
How to stream CMSampleBuffer to file in Swift?
 
 
Q