generator_demo.gd 761 B

12345678910111213141516171819202122232425262728
  1. extends Node
  2. var sample_hz = 22050.0 # Keep the number of samples to mix low, GDScript is not super fast.
  3. var pulse_hz = 440.0
  4. var phase = 0.0
  5. var playback: AudioStreamPlayback = null # Actual playback stream, assigned in _ready().
  6. func _fill_buffer():
  7. var increment = pulse_hz / sample_hz
  8. var to_fill = playback.get_frames_available()
  9. while to_fill > 0:
  10. playback.push_frame(Vector2.ONE * sin(phase * TAU)) # Audio frames are stereo.
  11. phase = fmod(phase + increment, 1.0)
  12. to_fill -= 1
  13. func _process(_delta):
  14. _fill_buffer()
  15. func _ready():
  16. $Player.stream.mix_rate = sample_hz # Setting mix rate is only possible before play().
  17. playback = $Player.get_stream_playback()
  18. _fill_buffer() # Prefill, do before play() to avoid delay.
  19. $Player.play()