可以在录制的同时将麦克风传递给音频引擎,延迟最小:
let audioEngine = AVAudioEngine()
...
self.audioEngine.connect(self.audioEngine.inputNode,
to: self.audioEngine.mainMixerNode, format: nil)
self.audioEngine.start()
如果样本缓冲区的使用很重要——大致可以通过转换为 PCM 缓冲区来完成:
import AVFoundation
extension AVAudioPCMBuffer {
static func create(from sampleBuffer: CMSampleBuffer) -> AVAudioPCMBuffer? {
guard let description: CMFormatDescription = CMSampleBufferGetFormatDescription(sampleBuffer),
let sampleRate: Float64 = description.audioStreamBasicDescription?.mSampleRate,
let channelsPerFrame: UInt32 = description.audioStreamBasicDescription?.mChannelsPerFrame /*,
let numberOfChannels = description.audioChannelLayout?.numberOfChannels */
else { return nil }
guard let blockBuffer: CMBlockBuffer = CMSampleBufferGetDataBuffer(sampleBuffer) else {
return nil
}
let samplesCount = CMSampleBufferGetNumSamples(sampleBuffer)
//let length: Int = CMBlockBufferGetDataLength(blockBuffer)
let audioFormat = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: sampleRate, channels: AVAudioChannelCount(1), interleaved: false)
let buffer = AVAudioPCMBuffer(pcmFormat: audioFormat!, frameCapacity: AVAudioFrameCount(samplesCount))!
buffer.frameLength = buffer.frameCapacity
// GET BYTES
var dataPointer: UnsafeMutablePointer<Int8>?
CMBlockBufferGetDataPointer(blockBuffer, atOffset: 0, lengthAtOffsetOut: nil, totalLengthOut: nil, dataPointerOut: &dataPointer)
guard var channel: UnsafeMutablePointer<Float> = buffer.floatChannelData?[0],
let data = dataPointer else { return nil }
var data16 = UnsafeRawPointer(data).assumingMemoryBound(to: Int16.self)
for _ in 0...samplesCount - 1 {
channel.pointee = Float32(data16.pointee) / Float32(Int16.max)
channel += 1
for _ in 0...channelsPerFrame - 1 {
data16 += 1
}
}
return buffer
}
}
class BufferPlayer {
let audioEngine = AVAudioEngine()
let player = AVAudioPlayerNode()
deinit {
self.audioEngine.stop()
}
init(withBuffer: CMSampleBuffer) {
self.audioEngine.attach(self.player)
self.audioEngine.connect(self.player,
to: self.audioEngine.mainMixerNode,
format: AVAudioPCMBuffer.create(from: withBuffer)!.format
)
_ = try? audioEngine.start()
}
func playEnqueue(buffer: CMSampleBuffer) {
guard let bufferPCM = AVAudioPCMBuffer.create(from: buffer) else { return }
self.player.scheduleBuffer(bufferPCM, completionHandler: nil)
if !self.player.isPlaying { self.player.play() }
}
}