1

我正在尝试使用 AVAssetwriter 录制视频。现在想控制我最终输出视频文件的音量。有什么帮助吗?

我尝试过的解决方案:-

  1. self.avAssetInputAudio?.preferredVolume = 0.2//此属性的值通常应在 0.0 到 1.0 的范围内。(相当于“正常”音量) https://developer.apple.com/documentation/avfoundation/avassetwriterinput/1389949-preferredvolume 输出:- 输出文件中的音量没有变化。

2.使用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
}

输出:- 最终音频断断续续且嘈杂。

4

0 回答 0