diff --git a/Main.tscn b/Main.tscn new file mode 100644 index 0000000..7a89188 --- /dev/null +++ b/Main.tscn @@ -0,0 +1,8 @@ +[gd_scene load_steps=2 format=2] + +[ext_resource path="res://Scenes/Conductor.tscn" type="PackedScene" id=1] + +[node name="Main" type="Node2D"] + +[node name="Conductor" parent="." instance=ExtResource( 1 )] +song_offset = 200000.0 diff --git a/Scenes/Conductor.tscn b/Scenes/Conductor.tscn new file mode 100644 index 0000000..5f333a7 --- /dev/null +++ b/Scenes/Conductor.tscn @@ -0,0 +1,12 @@ +[gd_scene load_steps=2 format=2] + +[ext_resource path="res://Scripts/Conductor.gd" type="Script" id=1] + + + + + +[node name="Conductor" type="Node"] +script = ExtResource( 1 ) + +[node name="Music" type="AudioStreamPlayer" parent="."] diff --git a/Scripts/Conductor.gd b/Scripts/Conductor.gd new file mode 100644 index 0000000..8ff069f --- /dev/null +++ b/Scripts/Conductor.gd @@ -0,0 +1,60 @@ +extends Node +class_name Conductor +# The Conductor (optionally) plays a song, and sends signals based on the beats of the song. + +# The beats per minute of the song +export(float, 1, 500) var song_bpm: float = 120 + +# Microseconds of silence present in the song +export(float, 0, 1000000) var song_offset: float = 0 + +# The time the song started playing at +var start_time: int + +# The time of the last beat +var last_beat: int + +# A song beat +signal beat + + +# Calculate the microseconds per beat +func usec_per_beat(): + return 60000000 / song_bpm + + +# Returns microseconds since the song start +func song_time(): + var current_time: int = OS.get_ticks_usec() + return current_time - start_time + +# Return corrected microseconds (after applying the offset) since the song start +func corrected_time(): + var song_time = song_time() + return song_time - song_offset + + +# Start playing the song +func play(): + start_time = OS.get_ticks_usec() + $Music.play() + + +# Signal that a beat has happened +func beat(): + pass + + +func _ready(): + play() + + +func _process(delta): + var time = corrected_time() + if time - last_beat >= usec_per_beat(): + emit_signal("beat") + last_beat = time + + +func _on_Conductor_beat(): + print("Beat! %f" % song_time()) diff --git a/project.godot b/project.godot index 1afcd19..69ecfff 100644 --- a/project.godot +++ b/project.godot @@ -8,14 +8,20 @@ config_version=4 -_global_script_classes=[ ] +_global_script_classes=[ { +"base": "Node", +"class": "Conductor", +"language": "GDScript", +"path": "res://Scripts/Conductor.gd" +} ] _global_script_class_icons={ - +"Conductor": "" } [application] config/name="ld47" +run/main_scene="res://Main.tscn" [rendering]