iosswiftavaudiorecorderamplitude

AVAudioRecorder! I need to have decibel values from amplitude on a scale of 0 to 120 ios swift?


I'm getting amplitude values from -70 to around 10 from AVAudioRecorder.peakPowerForChannel(0).I need the values on a scale of 0 to 120 how i do it. I need to get the highest value in amplitude from the whole audio. Seen this code on internet

var numver = 20 * log10(audioRecorder.peakPowerForChannel(0))

but this gives a value nan(Not a number).How can I get values of amplitude in positive range.


Solution

  • The function peakPowerForChannel() normally returns a logarithmically scaled decibel value from -160 dB to 0 dB.

    It can return a value greater than zero when the power exceeds the level for 0 dB.

    To convert to a linear scale for values from 0 to 120, please use the following formula.

    let db = audioRecorder.peakPowerForChannel(0)
    let result = pow(10.0, db / 20.0) * 120.0
    

    You can choose whether to keep or discard values that exceed 120 with a max() or min() function.