Skip to content

Instantly share code, notes, and snippets.

@RichardEllicott
Last active November 30, 2024 00:53
Show Gist options
  • Save RichardEllicott/9515782f8bbf55748993f30548652581 to your computer and use it in GitHub Desktop.
Save RichardEllicott/9515782f8bbf55748993f30548652581 to your computer and use it in GitHub Desktop.
"""
corrects flaws from:
https://docs.godotengine.org/en/stable/classes/class_audiostreamgenerator.html
"""
@tool
extends Node
var playback: AudioStreamGeneratorPlayback # Will hold the AudioStreamGeneratorPlayback.
@onready var sample_hz: float = $AudioStreamPlayer.stream.mix_rate
var pulse_hz: float = 440.0 # The frequency of the sound wave.
var phase: float = 0.0 // phase now stored between buffer updates (so the sine wave all lines up)
@export var enabled := false // enable to here to sound
func _process(delta: float) -> void:
if not enabled: return
fill_buffer() // try to fill buffer each frame
func _ready() -> void:
$AudioStreamPlayer.play()
playback = $AudioStreamPlayer.get_stream_playback()
fill_buffer()
func fill_buffer():
var increment: float = pulse_hz / sample_hz
var frames_available: int = playback.get_frames_available() # check how many frames we can fill
for i in range(frames_available):
playback.push_frame(Vector2.ONE * sin(phase * TAU))
phase = fmod(phase + increment, 1.0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment