From 2e8c94181232b42c3b62140e1f9f3a81d425ac89 Mon Sep 17 00:00:00 2001 From: Lane Barnes Date: Sat, 23 Nov 2024 15:36:03 -0700 Subject: [PATCH] Fix example code snippet in AudioStreamGenerator.xml I was playing around with C# code snippet but I kept hearing a clipping sound. I think this is because the phase variable is being set to 0 in the wrong spot. The phase at the end of the FillBuffer() method is some non zero number. When FillBuffer is called again, the phase is suddenly changed back to zero. This causes the end of one sin wave segment to be out of sync with the next sin wave segment. The sin wave needs to be continuous between FillBuffer calls so no clipping sound occurs. Moving the phase variable out of FillBuffer and putting it in a scope above makes it retain its value between FillBuffer calls, making the sin wave continuous, and the clipping sound is gone. For further proof, the demo project "Audio Generator Demo" has the phase variable be one scope above FillBuffer and it does not set phase=0 inside of FillBuffer. If anything, I'm fixing this documentation to match the working demo --- doc/classes/AudioStreamGenerator.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/classes/AudioStreamGenerator.xml b/doc/classes/AudioStreamGenerator.xml index f618e69631e..6fce5a8af15 100644 --- a/doc/classes/AudioStreamGenerator.xml +++ b/doc/classes/AudioStreamGenerator.xml @@ -11,6 +11,7 @@ var playback # Will hold the AudioStreamGeneratorPlayback. @onready var sample_hz = $AudioStreamPlayer.stream.mix_rate var pulse_hz = 440.0 # The frequency of the sound wave. + var phase = 0.0 func _ready(): $AudioStreamPlayer.play() @@ -18,7 +19,6 @@ fill_buffer() func fill_buffer(): - var phase = 0.0 var increment = pulse_hz / sample_hz var frames_available = playback.get_frames_available() @@ -32,6 +32,7 @@ private AudioStreamGeneratorPlayback _playback; // Will hold the AudioStreamGeneratorPlayback. private float _sampleHz; private float _pulseHz = 440.0f; // The frequency of the sound wave. + private double phase = 0.0; public override void _Ready() { @@ -46,7 +47,6 @@ public void FillBuffer() { - double phase = 0.0; float increment = _pulseHz / _sampleHz; int framesAvailable = _playback.GetFramesAvailable();