Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save noidexe/c770b7afdee10feefb1ba2fc35d1eaa2 to your computer and use it in GitHub Desktop.
Save noidexe/c770b7afdee10feefb1ba2fc35d1eaa2 to your computer and use it in GitHub Desktop.
AudioStreamPlayer with a counter, which counts the seconds elapsed and emits a signal each second
extends AudioStreamPlayer
class_name AudioStreamPlayerWithCounter
signal playback_position_reached(number)
var counter: int = 0
var trigger_map = {}
class Trigger extends Reference:
var _target : Object
var _method : String
var _args := []
func _init(t: Object, m: String, a:= []):
assert(is_instance_valid(t))
assert(t.has_method(m))
_target = t
_method = m
_args = a
func execute():
if not is_instance_valid(_target):
return
_target.callv(_method, _args)
func _ready() -> void:
if not stream:
set_process(false)
func _process(_delta: float) -> void:
var play_pos = int(get_playback_position())
if play_pos != counter:
counter = play_pos
emit_signal("playback_position_reached", counter)
for t in trigger_map.get(counter, []):
t.execute()
trigger_map.erase(counter)
func call_at( seconds: int, target: Object, method: String, args := []) -> bool:
if get_playback_position() > counter:
push_warning("Call seconds already elapsed")
return false
var trigger = Trigger.new(target, method, args)
if not trigger_map.has(seconds):
trigger_map[seconds] = []
trigger_map[seconds].append(trigger)
return true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment