I am trying to record a video with AVAssetwriter. Now want to control volume for my final output video file. Any Help?
Solutions I had tried:-
self.avAssetInputAudio?.preferredVolume = 0.2
//The value for this property should typically be in the range of 0.0 to 1.0. (which is equivalent to a “normal” volume level) https://developer.apple.com/documentation/avfoundation/avassetwriterinput/1389949-preferredvolume Output:- No change in volume level in the output file.
2.Processing Audio with CMSampleBuffer
func processSampleBuffer(scale: Float, sampleBuffer: CMSampleBuffer, writerInput: AVAssetWriterInput) -> Bool {
guard let blockBuffer = CMSampleBufferGetDataBuffer(sampleBuffer) else {
return false
}
let length = CMBlockBufferGetDataLength(blockBuffer)
var sampleBytes = UnsafeMutablePointer<Int16>.allocate(capacity: length)
defer { sampleBytes.deallocate(capacity: length) }
guard checkStatus(CMBlockBufferCopyDataBytes(blockBuffer, 0, length, sampleBytes), message: "Copying block buffer") else {
return false
}
(0..<length).forEach { index in
let ptr = sampleBytes + index
let scaledValue = Float(ptr.pointee) * scale
let processedValue = Int16(max(min(scaledValue, Float(Int16.max)), Float(Int16.min)))
ptr.pointee = processedValue
}
guard checkStatus(CMBlockBufferReplaceDataBytes(sampleBytes, blockBuffer, 0, length), message: "Replacing data bytes in block buffer") else { return false }
assert(CMSampleBufferIsValid(sampleBuffer))
return writerInput.append(sampleBuffer)
}
func checkStatus(_ status: OSStatus, message: String) -> Bool {
assert(kCMBlockBuferNoErr == noErr)
if status != noErr {
debugPrint("Error: \(message) [\(status)]")
}
return status == noErr
}
output:- Final audio is choppy and noisy.