Преглед изворни кода

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
Lane Barnes пре 9 месеци
родитељ
комит
2e8c941812
1 измењених фајлова са 2 додато и 2 уклоњено
  1. 2 2
      doc/classes/AudioStreamGenerator.xml

+ 2 - 2
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();