swift iOS - 无法从 tracker.frequency audiokit 输出创建数组

swift iOS - Not able to create array from tracker.frequency audiokit output

我在我的应用程序中使用 AudioKit 麦克风分析来检测声音频率。一切正常,但是,我想捕获前几个(可能是 20 到 30 个)频率并将其存储在一个数组中。我可以使用 print(tracker.frequency) 打印频率。我正在尝试在空数组上使用插入来存储

这是我的视图控制器中的代码

@objc func updateUI() {
    if tracker.amplitude > 0.01 {
        frequencyLbl.text = String(format: "%0.1f", tracker.frequency)

        var frequency = Float(tracker.frequency)


        while frequency > Float(noteFrequencies[noteFrequencies.count - 1]) {
            frequency /= 2.0

        }
        while frequency < Float(noteFrequencies[0]) {
            frequency *= 2.0
        }
        // This is not working. I need an array like [23.111, 234.555, 345.65.. etc]
        var dynamicFrequency: [Float] = [frequency]
        for f in dynamicFrequency {
           dynamicFrequency.insert(f, at: 0)
        }
        print(dynamicFrequency)


        var minDistance: Float = 10_000.0
        var index = 0

        for i in 0..<noteFrequencies.count {
            let distance = fabsf(Float(noteFrequencies[i]) - frequency)
            if distance < minDistance {
                index = i
                minDistance = distance
            }
        }
        let octave = Int(log2f(Float(tracker.frequency) / frequency))
        noteNameLbl.text = "\(noteNamesWithSharps[index])\(octave)"
        noteNameFlatsLbl.text = "\(noteNamesWithFlats[index])\(octave)"



    }
    amplitudeLbl.text = String(format: "%0.2f", tracker.amplitude)

}

输出显示如下

AKMicrophone.swift:init():45:Mixer inputs 8
Audio Kit Started
[27.1829815, 27.1829815]
[16.7672386, 16.7672386]
[32.2606049, 32.2606049]
[31.2773647, 31.2773647]
[31.2035122, 31.2035122]
[31.5194035, 31.5194035]
[32.4384956, 32.4384956]
[25.3139915, 25.3139915]
[28.1445961, 28.1445961]

但是,我希望输出为

    [27.1829815,16.7672386,32.2606049,31.2773647,31.2035122,31.5194035,32.43849 56,25.3139915,28.1445961]

我做错了什么?

您似乎经常打电话给 updateUI()。这就是 dynamicFrequency 被多次打印的原因。 要获得所需的输出,您必须做的是在 updateUI() 之外声明 dynamicFrequency 并在它具有 20 个左右的频率后打印其内容:

var dynamicFrequency: [Float] = [frequency]
@objc func updateUI() {
    //...
    for f in dynamicFrequency {
        dynamicFrequency.insert(f, at: 0)
    }
    if dynamicFrequency.count == 20 {
        print(dynamicFrequency)
        //The following line would be optional 
        //if you'd like to empty the dynamicFrequency 
        //once you print its contents
        dynamicFrequency.removeAll()
    }
    //...
}