generator_demo.gd 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. # Setting mix rate is only possible before play().
  17. $Player.stream.mix_rate = sample_hz
  18. $Player.play()
  19. playback = $Player.get_stream_playback()
  20. # `_fill_buffer` must be called *after* setting `playback`,
  21. # as `fill_buffer` uses the `playback` member variable.
  22. _fill_buffer()
  23. func _on_frequency_h_slider_value_changed(value):
  24. %FrequencyLabel.text = "%d Hz" % value
  25. pulse_hz = value
  26. func _on_volume_h_slider_value_changed(value):
  27. # Use `linear_to_db()` to get a volume slider that matches perceptual human hearing.
  28. %VolumeLabel.text = "%.2f dB" % linear_to_db(value)
  29. $Player.volume_db = linear_to_db(value)