Skip to content

Instantly share code, notes, and snippets.

@ngs
Created May 14, 2018 09:31
Show Gist options
  • Select an option

  • Save ngs/575f6422b31fa2f0e3cf6b276d59b1f0 to your computer and use it in GitHub Desktop.

Select an option

Save ngs/575f6422b31fa2f0e3cf6b276d59b1f0 to your computer and use it in GitHub Desktop.
//
// AVAudioPCMBufferExtension.swift
//
// Created by Atsushi Nagase on 2018/05/14.
// Copyright © 2018 LittleApps Inc. All rights reserved.
//
import Speech
extension AVAudioPCMBuffer {
// https://stackoverflow.com/a/50237644
func volume(for bufferSize: Int) -> Float {
guard let channelData = floatChannelData?[0] else {
return 0
}
let channelDataArray = Array(UnsafeBufferPointer(start:channelData, count: bufferSize))
var outEnvelope = [Float]()
var envelopeState:Float = 0
let envConstantAtk:Float = 0.16
let envConstantDec:Float = 0.003
for sample in channelDataArray {
let rectified = abs(sample)
if envelopeState < rectified {
envelopeState += envConstantAtk * (rectified - envelopeState)
} else {
envelopeState += envConstantDec * (rectified - envelopeState)
}
outEnvelope.append(envelopeState)
}
// 0.007 is the low pass filter to prevent
// getting the noise entering from the microphone
if let maxVolume = outEnvelope.max(),
maxVolume > Float(0.015) {
return maxVolume
} else {
return 0.0
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment