Skip to content

Instantly share code, notes, and snippets.

@0187773933
Created April 2, 2024 20:08
Show Gist options
  • Save 0187773933/8de26d264d6e605cf3ce9ea702104a6d to your computer and use it in GitHub Desktop.
Save 0187773933/8de26d264d6e605cf3ce9ea702104a6d to your computer and use it in GitHub Desktop.
Watch Microphone Audio Stream DB Level
package main
import (
"fmt"
"math"
"github.com/gordonklaus/portaudio"
)
const sample_rate = 44100
const buffer_size = 64 // Number of samples per buffer
var frames_per_buffer = make( []float32 , buffer_size )
const average_duration_seconds = 5 // time window for moving average
var moving_average_buffers = int( sample_rate * average_duration_seconds / buffer_size )
var spl_ring_buffer = make( []float64 , moving_average_buffers )
var spl_index int = 0
func CalculateSPL( buffer []float32 ) float64 {
var sum_squares float64
for _ , sample := range buffer {
sum_squares += float64( sample ) * float64( sample )
}
rms := math.Sqrt( sum_squares / float64( len( buffer ) ) )
spl := 20 * math.Log10( rms / ( 20e-6 ) )
return spl
}
func CalculateMovingAverageSPL( spl float64 ) float64 {
// Update the ring buffer with the latest SPL
spl_ring_buffer[ spl_index ] = spl
spl_index = ( spl_index + 1 ) % moving_average_buffers
// Calculate the moving average
var sum float64
for _ , val := range spl_ring_buffer {
sum += val
}
return sum / float64( moving_average_buffers )
}
// https://github.com/gordonklaus/portaudio
func main() {
portaudio.Initialize()
defer portaudio.Terminate()
devices , err := portaudio.Devices()
if err != nil { panic( err ) }
var our_device *portaudio.DeviceInfo
for _ , device := range devices {
if device.Name == "XS02 USB" {
our_device = device
}
}
fmt.Println( our_device )
// frames_per_buffer := make( []float32 , buffer_size )
// mic_params := portaudio.StreamParameters{
// Input: portaudio.StreamDeviceParameters{
// Device: our_device ,
// Channels: 2 ,
// Latency: our_device.DefaultLowInputLatency ,
// },
// SampleRate: sample_rate ,
// FramesPerBuffer: frames_per_buffer ,
// }
// stream , err := portaudio.OpenStream( mic_params , nil )
stream , err := portaudio.OpenDefaultStream( 2 , 0 , sample_rate , buffer_size , &frames_per_buffer )
if err != nil { panic( err ) }
fmt.Println( stream )
defer stream.Close()
err = stream.Start()
if err != nil { panic( err ) }
for {
err = stream.Read()
if err != nil { panic( err ) }
// fmt.Println( frames_per_buffer )
// Process framesPerBuffer to calculate SPL
spl := CalculateSPL( frames_per_buffer )
moving_average_spl := CalculateMovingAverageSPL( spl )
fmt.Printf( "Current SPL: %f dB, Moving Average SPL: %f dB\n" , spl , moving_average_spl )
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment