Smartphone microphones are not calibrated for accurate dB measurements.
The values obtained are often in dBFS (decibels full scale), not dB SPL (actual sound pressure).
dBFS isn't an absolute measurement like dB SPL (actual sound pressure), but it does give you a relative volume value.
Very loud sounds (>90 dB SPL) may be misrecorded or distorted.
We will use the microphone to capture the ambient sound (i.e. what comes out of the speaker) and analyze this signal in real time to extract an approximate value in dB.
We use AudioRecord to capture sound without recording it, calculate the RMS (Root Mean Square) level and convert it to dBFS in real time.
Sub Class_Globals
Private Root As B4XView
Private xui As XUI
Private rp As RuntimePermissions
Private audio As AudioRecord
Private bufferSize As Int
Private Timer1 As Timer
End Sub
Public Sub Initialize
' B4XPages.GetManager.LogEvents = True
End Sub
'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
Root = Root1
Root.LoadLayout("MainPage")
rp.CheckAndRequest("android.permission.RECORD_AUDIO")
' Initialisation
bufferSize = audio.GetMinBufferSize(44100, audio.CH_CONF_MONO, audio.AF_PCM_16)
audio.Initialize(audio.A_SRC_MIC, 44100, audio.CH_CONF_MONO, audio.AF_PCM_16, bufferSize)
' Timer to measure every 500ms
Timer1.Initialize("Timer1", 500)
Timer1.Enabled = True
End Sub
Sub Timer1_Tick
' Read audio data
Dim samples() As Short = audio.ReadShort(0, bufferSize / 2) ' each sample = 2 bytes
' Calculation RMS
Dim sum As Double = 0
For Each s As Short In samples
sum = sum + s * s
Next
Dim rms As Double = Sqrt(sum / samples.Length)
' Conversion to dBFS
Dim dbfs As Double = 20 * Logarithm(rms / 32768, 10)
Log("Noise level (dBFS) : " & NumberFormat(dbfs, 1, 2))
End Sub
Private Sub Button1_Click
audio.Initialize(audio.A_SRC_MIC, 44100, audio.CH_CONF_MONO, audio.AF_PCM_16, bufferSize)
audio.StartRecording
End Sub
You can manually calibrate by comparing it with a physical sound level meter if you want more precision.
You're not recording anything here, just a direct reading from the microphone.
Have fun