Godot Version
v4.6.stable.official [89cea1439]
How best to replicate AudioStreamRandomizer in GDScript?
Right now, I have code like this. It’s similar to an AudioStreamRandomizer, but it provides a single stream, with controls over the playback. For example pitch and a db offset.
extends AudioStream
class_name SoundEffect
@export var stream : AudioStream
@export var pitch : float = 1.0
@export var db_offset : float = 0.0
func _instantiate_playback() -> AudioStreamPlayback:
var playback = stream.instantiate_playback()
playback.start()
return playback
Setup
As far as I can tell, there are a few moving pieces:
- The audio stream, which allows creating a playback. For now I can rely on
instantiate_playbackwithin my stream. - The
AudioStreamPlaybackitself.
I believe AudioStreamRandomizer resource uses a playback called AudioStreamPlaybackRandomizer which isn’t exposed to GDScript. I think this is where the volume and pitch is set.
In any case, I think the control is handled here:
int AudioStreamPlaybackRandomizer::mix(AudioFrame *p_buffer, float p_rate_scale, int p_frames) {
if (playing.is_valid()) {
int mixed_samples = playing->mix(p_buffer, p_rate_scale * pitch_scale, p_frames);
for (int samp = 0; samp < mixed_samples; samp++) {
p_buffer[samp] *= volume_scale;
}
return mixed_samples;
} else {
for (int i = 0; i < p_frames; i++) {
p_buffer[i] = AudioFrame(0, 0);
}
return p_frames;
}
}
But there is this in the docs:
Override this method to customize how the audio stream is mixed. This method is called even if the playback is not active.
Note: It is not useful to override this method in GDScript or C#. Only GDExtension can take advantage of it.
So it seems like I might be blocked…? Any ideas?