AKAmplitudeTracker amplitude getting 0.0 using audioKit

194 Views Asked by At

I want to get the volume of AKAmplitudeTracker but getting -inf what is wrong with me please help out.

    AKAudioFile.cleanTempDirectory()
    AKSettings.audioInputEnabled = true
    AKSettings.bufferLength = .medium
    AKSettings.defaultToSpeaker = true
    AKSettings.playbackWhileMuted = true
    AKSettings.enableRouteChangeHandling = true
    AKSettings.enableCategoryChangeHandling = true
     AKSettings.enableLogging = true
    do {
        try AKSettings.setSession(category: .playAndRecord, with: .allowBluetoothA2DP)
    } catch {
        print("error \(error.localizedDescription)")
    }

    microphone = AKMicrophone()!


    tracker = AKAmplitudeTracker(microphone)
    booster = AKBooster(tracker, gain: 0)
    AudioKit.output = booster
    try AudioKit.start()

=================

extension AKAmplitudeTracker {

    var volume: Decibel {
        return 20.0 * log10(amplitude)
    }
}

=================

OutPut print(tracker. amplitude)

0.0
1

There are 1 best solutions below

0
On

Had a quick look, seems that you followed the basic setup, you do seem to fail to trace the data generated in time correctly! Amplitude data is provided during the time period for the computation that is taken from the microphone, so to look at what it looks like in timeline you can use a timer, as such:

func reset() throws {
    do {
        self.timer.invalidate()
        self.timer = nil
    } catch {
        throw error
    }
}

func microphoneTracker() {
    guard self.timer == nil else { return }
    self.watcher()
    let timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { _ in

         log.info(self.akMicrophoneAmplitudeTracker.amplitude)
    }

    self.timer = timer
}

Change the withTimeInterval to how frequently you want to check the amplitude.

I think it's quite readable what I put there for you, but I'll break it down in a few words:

  • Keep a reference for the AKAmplitudeTracker in a property, here I've named it akMicrophoneAmplitudeTracker
  • Keep a reference for your timed event, that will check the amplitude value during a period
  • Compute the data in the closure body, the property holding value is .amplitude
  • The computation in the example is a logger that prints .amplitude
  • As required, use the .invalidate method to stop the timer

A few other things you may want to double-check on your code is to make sure that the tracker is part of the signal chain, as that's an AVAudioEngine engine requirement; I've also noticed in some other people's code a call for the method .start in the AKAmplitudeTracker, as follows:

akMicrophoneAmplitudeTracker.start()

To finish, have in mind that if you are testing it through Simulator, look at the microphone settings of your host-machine and expect amplitudes that might be different then the actual hardware.