Swift - How to get current volume from mic input (AVAudioPCMBuffer)

I am recording audio from a microphone and transferring it to another device. Currently, this audio is streamed even when the user is not talking. But I've noticed that many streaming services don't actually send your mic input when they find that there is very little noise from it.

So my question is how do I see how loud the input is before passing it to another device.

I am recording audio using the AVAudioPlayerNode attached to the AVAudioEngine. Then I use the following entries:

localInput?.installTap(onBus: 0, bufferSize: 4096, format: localInputFormat) {
    (buffer, when) -> Void in

      

Here the buffer is AVAudioPCMBuffer, so I need to see the volume from that buffer.

Thank!

+3


source to share


1 answer


I was able to do it using the following code:

            let arraySize = Int(buffer.frameLength)
            var channelSamples: [[DSPComplex]] = []
            let channelCount = Int(buffer.format.channelCount)

            for i in 0..<channelCount {

                channelSamples.append([])
                let firstSample = buffer.format.isInterleaved ? i : i*arraySize

                for j in stride(from: firstSample, to: arraySize, by: buffer.stride*2) {

                    let channels = UnsafeBufferPointer(start: buffer.floatChannelData, count: Int(buffer.format.channelCount))
                    let floats = UnsafeBufferPointer(start: channels[0], count: Int(buffer.frameLength))
                    channelSamples[i].append(DSPComplex(real: floats[j], imag: floats[j+buffer.stride]))

                }
            }

            var spectrum = [Float]()

            for i in 0..<arraySize/2 {

                let imag = channelSamples[0][i].imag
                let real = channelSamples[0][i].real
                let magnitude = sqrt(pow(real,2)+pow(imag,2))

                spectrum.append(magnitude)
            }

      



Credit for this answer goes to question .

+1


source







All Articles