dmrschmidt / DSWaveformImage

Generate waveform images from audio files on iOS, macOS & visionOS in Swift. Native SwiftUI & UIKit views.
MIT License
978 stars 109 forks source link

Current amplitude #70

Closed Patresko closed 1 year ago

Patresko commented 1 year ago

I take this one from an example

1 - pow(10, recorder.averagePower(forChannel: 0) / 20)

But this giving very strange results in real scenarions. I have tried muted mic and I was receiving averagePower -120 and amplitude 0.999999.

When I unmuted mic, my level was between -30 to -50 but difference in amplitude was too small to see any difference in waves.

Few logs from console

Adjusted value is from the function above. Mic power is recorder.averagePower

MIC POWER: -64.33277 ADJUSTED: 0.99939275
MIC POWER: -63.291 ADJUSTED: 0.9993154
MIC POWER: -62.035603 ADJUSTED: 0.9992089
MIC POWER: -62.04938 ADJUSTED: 0.9992102
MIC POWER: -60.18708 ADJUSTED: 0.9990213

In my code


timer = Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true, block: { (timer) in

   self.audioRecorder.updateMeters()

    let linear = 1 - pow(10, self.audioRecorder.averagePower(forChannel: 0) / 20)
    print("MIC POWER: \(self.audioRecorder.averagePower(forChannel: 0)) ADJUSTED: \(linear)")

     self.recordingTime = self.audioRecorder.currentTime
     self.samples.append(linear)
})```
dmrschmidt commented 1 year ago

What you observed is what you should expect to see in this example, yes.

You can see that averagePower(forChannel:) returns values in dBFS, between -160dBFS and 0 (being maximum loudness that can be represented). The formula translates that decibel value back to an amplitude between (0...1). See wikipedia or this article for instance which is a less mathematical.

If you'd like different scaling, you may map the dB value to (0...1) in any other way you may prefer, eg by dividing by -160 or similar.