Created
April 20, 2022 21:44
-
-
Save vzsg/ef7a46711cb4ed211664d21395b2bdf9 to your computer and use it in GitHub Desktop.
MeterTableOC Swift port
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
struct MeterTable { | |
private let minDecibels: Double | |
private let scaleFactor: Double | |
private let table: [Double] | |
init(minDB: Double = -80, tableSize: Int = 400, root: Double = 2) { | |
self.minDecibels = minDB | |
let decibelResolution = minDecibels / (Double(tableSize) - 1) | |
self.scaleFactor = 1.0 / decibelResolution | |
let minAmp = dbToAmp(minDB) | |
let ampRange = 1.0 - minAmp | |
let invAmpRange = 1.0 / ampRange | |
let rRoot = 1.0 / root | |
var table = [Double]() | |
for i in 0..<tableSize { | |
let decibels = Double(i) * decibelResolution | |
let amp = dbToAmp(decibels) | |
let adjAmp = (amp - minAmp) * invAmpRange | |
table.append(pow(adjAmp, rRoot)) | |
} | |
self.table = table | |
} | |
func valueAt(_ decibels: Double) -> Double { | |
if decibels < minDecibels { | |
return 0 | |
} | |
if decibels >= 0 { | |
return 1 | |
} | |
let index = Int(decibels * scaleFactor) | |
guard index < table.count else { | |
return 1 | |
} | |
return table[index] | |
} | |
} | |
private func dbToAmp(_ db: Double) -> Double { | |
pow(10, 0.05 * db) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment