How to reduce CMSampleBuffer volume

Hello,

Basically, I am reading and writing an asset.
To simplify, I am just reading the asset and rewriting it into an output video without any modifications.

However, I want to add a fade-out effect to the last three seconds of the output video.

I don’t know how to do this.

So far, before adding the CMSampleBuffer to the output video, I tried reducing its volume using an extension on CMSampleBuffer.

In the extension, I passed 0.4 for testing, aiming to reduce the video's overall volume by 60%.

My question is:

How can I directly adjust the volume of a CMSampleBuffer?

Here is the extension:

extension CMSampleBuffer {
    func adjustVolume(by factor: Float) -> CMSampleBuffer? {
        guard let blockBuffer = CMSampleBufferGetDataBuffer(self) else { return nil }
        
        var length = 0
        var dataPointer: UnsafeMutablePointer<Int8>?
        
        guard CMBlockBufferGetDataPointer(blockBuffer, atOffset: 0, lengthAtOffsetOut: nil, totalLengthOut: &length, dataPointerOut: &dataPointer) == kCMBlockBufferNoErr else { return nil }
        
        guard let dataPointer = dataPointer else { return nil }
        
        let sampleCount = length / MemoryLayout<Int16>.size
        dataPointer.withMemoryRebound(to: Int16.self, capacity: sampleCount) { pointer in
            for i in 0..<sampleCount {
                let sample = Float(pointer[i])
                pointer[i] = Int16(sample * factor)
            }
        }
        
        return self
    }
}
How to reduce CMSampleBuffer volume
 
 
Q