diary/system/call/call_singleton.gd
2022-06-28 21:51:50 +02:00

107 lines
2.7 KiB
GDScript

extends Node
# warning-ignore:unused_signal
signal requested
signal accepted
signal closed
signal mute_toggled(value)
signal microphone_input_state_changed
const MUTE_SOUND = preload("res://sounds/mute.wav")
const UNMUTE_SOUND = preload("res://sounds/unmute.wav")
var is_active: bool = false
var is_accepted: bool = false
var is_muted: bool = false
var spectrum_analyizer: AudioEffectSpectrumAnalyzerInstance
var audio_stream_player: AudioStreamPlayer
var audio_stream_microphone: AudioStreamPlayer
var microphone_magnitude: float
var microphone_input_detected = false
var activity_value = 1.0
var activity_velocity = 0.0
func _ready():
var idx = AudioServer.get_bus_index("Recorder")
spectrum_analyizer = AudioServer.get_bus_effect_instance(idx, 0)
audio_stream_microphone = AudioStreamPlayer.new()
audio_stream_microphone.stream = AudioStreamMicrophone.new()
audio_stream_microphone.bus = "Recorder"
audio_stream_microphone.autoplay = true
add_child(audio_stream_microphone)
audio_stream_player = AudioStreamPlayer.new()
add_child(audio_stream_player)
var t = 0.0
func _process(delta):
var interval = 0.04
t += delta
while t > interval:
_check_for_microphone_input()
t -= interval
_check_for_hit_up(delta)
func request_call():
is_active = true
_reset_activity_stats()
emit_signal("requested")
func close_call():
is_active = false
is_accepted = false
emit_signal("closed")
func toggle_mute():
if is_muted:
audio_stream_player.stream = UNMUTE_SOUND
else:
audio_stream_player.stream = MUTE_SOUND
audio_stream_player.play()
is_muted = !is_muted
emit_signal("mute_toggled", is_muted)
func _check_for_microphone_input():
microphone_magnitude *= 0.92
var magnitude = spectrum_analyizer.get_magnitude_for_frequency_range(
80.0, 255.0, AudioEffectSpectrumAnalyzerInstance.MAGNITUDE_MAX
).length()
if microphone_magnitude < magnitude:
microphone_magnitude = magnitude
var above_threshold = Settings.microphone_threshold < microphone_magnitude
if above_threshold != microphone_input_detected:
microphone_input_detected = above_threshold
emit_signal("microphone_input_state_changed")
func _check_for_hit_up(delta): # Rather helper account should ping or not.
if not is_active:
return
if is_muted:
activity_velocity += delta * 0.5
else:
activity_velocity += delta * (1.3 if microphone_input_detected else -1.2)
activity_velocity = clamp(activity_velocity, -1.0, 1.0)
var delay = 0.066 / (1.0 + PingSystem.unhandled_ping_list.size() * 1.5)
activity_value += activity_velocity * delta * delay
activity_value = clamp(activity_value, -0.2, 1.0)
if activity_value <= 0.0:
PingSystem.send_ping(Time.get_current_time())
_reset_activity_stats()
func _reset_activity_stats():
activity_value = 1.0
activity_velocity = 0.0