I want to use this code for VoIP service.
i'm using web-socket and sending with it: let data = self.toNSData(PCMBuffer: buffer)
and playback:let audioBuffer = self.toPCMBuffer(data: data)
in another device)
I'm used: https://github.com/Lkember/IntercomTest and worked it but the size of data is big. I'm feeling 41100 rates is a very big size for send data, I want to reduce buffer size with the lower rate to 8000.
but I do not know how to reduce sample rate without according error!
my failing code is below:
@IBAction func start(_ sender: Any) {
var engine = AVAudioEngine()
let input = engine.inputNode
let bus = 0
let localAudioPlayer: AVAudioPlayerNode = AVAudioPlayerNode()
let mixer = AVAudioMixerNode()
let fmt = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 8000, channels: 1, interleaved: false)
engine.attach(mixer)
engine.connect(input, to: mixer, format: input.outputFormat(forBus: 0))
mixer.volume = 0
engine.connect(mixer, to: localAudioPlayer, format: fmt)
localAudioPlayer.installTap(onBus: bus, bufferSize: 512, format: fmt) { (buffer, time) -> Void in
// 8kHz buffers!
print(buffer.format)
localAudioPlayer.scheduleBuffer(buffer)
}
let data = self.toNSData(PCMBuffer: buffer)
let audioBuffer = self.toPCMBuffer(data: data)
localAudioPlayer.scheduleBuffer(audioBuffer)
if (!localAudioPlayer.isPlaying) {
localAudioPlayer.play()
try! engine.start()
}
}
func toNSData(PCMBuffer: AVAudioPCMBuffer) -> NSData {
let channelCount = 1 // given PCMBuffer channel count is 1
let channels = UnsafeBufferPointer(start: PCMBuffer.floatChannelData, count: channelCount)
let ch0Data = NSData(bytes: channels[0], length:Int(PCMBuffer.frameCapacity * PCMBuffer.format.streamDescription.pointee.mBytesPerFrame))
return ch0Data
}
func toPCMBuffer(data: NSData) -> AVAudioPCMBuffer {
let audioFormat = AVAudioFormat(commonFormat: AVAudioCommonFormat.pcmFormatFloat32, sampleRate: 8000, channels: 1, interleaved: false) // given NSData audio format
let PCMBuffer = AVAudioPCMBuffer(pcmFormat: audioFormat, frameCapacity: UInt32(data.length) / audioFormat.streamDescription.pointee.mBytesPerFrame)
PCMBuffer.frameLength = PCMBuffer.frameCapacity
let channels = UnsafeBufferPointer(start: PCMBuffer.floatChannelData, count: Int(PCMBuffer.format.channelCount))
data.getBytes(UnsafeMutableRawPointer(channels[0]) , length: data.length)
return PCMBuffer
}