extends Node

var mic_stream: AudioStreamMicrophone
var spectrum_instance: AudioEffectSpectrumAnalyzerInstance

func _ready():
	mic_stream = AudioStreamMicrophone.new()
	$".".stream = mic_stream
	$".".bus = "Record"
	$".".play()

	# Get the Spectrum Analyzer instance from the audio bus
	var bus_index = AudioServer.get_bus_index("Record")
	var spectrum_effect = AudioServer.get_bus_effect(bus_index, 0) # 0 for the first effect
	if spectrum_effect is AudioEffectSpectrumAnalyzer:
		spectrum_instance = AudioServer.get_bus_effect_instance(bus_index, 0)
	else:
		print("Spectrum Analyzer effect not found on Record")

func _process(_delta):
	if spectrum_instance:
		var magnitude = spectrum_instance.get_magnitude_for_frequency_range(20, 20000)
		var max_magnitude = magnitude.x

		# Convert magnitude to dB
		var db = linear_to_db(max_magnitude)
		print("Volume (dB): ", db)

		if State.blower_up:
			if db > -50:
				State.blowing = true
			else:
				State.blowing = false


# Convert linear magnitude to decibels
func linear_to_db(linear: float) -> float:
	if linear <= 0.0001: # Avoid log of zero
		return -80.0 # Silence threshold
	return 20.0 * (log(linear) / log(10))
