Aron Aron - 5 months ago 19
Swift Question

How can i return the values of a void function

I have a function that calculate the fft of the mic input.
The target is to create a framework when i call the run function the i ged the float array with all bands.

Now it work all fine, but i don't know how can i return the Array in the run function from the gotSomeAudio function.

Thank you very much for help

@objc
public class FFT:NSObject{


var audioInput: TempiAudioInput!

@objc
public func run() -> Array<Float>{

let audioInputCallback: TempiAudioInputCallback = { (numberOfFrames, timeStamp, inout samples: [Float]) -> Void in
self.gotSomeAudio(numberOfFrames, timeStamp: timeStamp, samples: samples)
}


audioInput = TempiAudioInput(audioInputCallback: audioInputCallback, sampleRate: 44100, numberOfChannels: 1)
audioInput.startRecording()

// how can i return the Array from the gotSomeAudio function?
return xyz
}




@objc
public func gotSomeAudio(numberOfFrames: Int, timeStamp: Double, samples: [Float]) -> Array<Float> {

let fft = TempiFFT(withSize: numberOfFrames, sampleRate: 44100)

// Setting a window type reduces errors
fft.windowType = TempiFFTWindowType.hanning

// Perform the FFT
fft.fftForward(samples)

// Map FFT data to logical bands. This gives 4 bands per octave across 7 octaves = 28 bands.
//fft.calculateLogarithmicBands(minFrequency: 100, maxFrequency: 11025, bandsPerOctave: 4)
//fft.calculateLinearBands(minFrequency: 0, maxFrequency: fft.nyquistFrequency, numberOfBands: Int(screenWidth))
fft.calculateLogarithmicBands(minFrequency: 100, maxFrequency: 11025, bandsPerOctave: 4)

// Process some data
return fft.bandFrequencies

}

}

Answer

You can pass it to a callback function:

public func run(complete: Array<Float> -> Void) {

    let audioInputCallback: TempiAudioInputCallback = { (numberOfFrames, timeStamp, inout samples: [Float]) -> Void in
        complete(self.gotSomeAudio(numberOfFrames, timeStamp: timeStamp, samples: samples))
    }

...

myInstance.run() { floatArray in
    // Use floatArray here.
}
Comments