Creating audio samples from PCM data at runtime

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Akorian

I wrote a GDNative plugin that generates an audio sample in a raw PCM format (2 channels 16 bit at a specified sampling rate) and stores it in a buffer.

Now, I want to create an audio sample in Godot from this data.
Is there any way to do this?

Solutions using either GDScript or GDNative would be great.

:bust_in_silhouette: Reply From: Akorian

After messing around with it some more I managed to solve this issue myself, here’s what I did:

I generated the PCM audio data as usual and returned it from GDNative back to GDScript as pool byte array. I then created a new AudioSampleStream in GDScript, set all the appropriate parameters and set the .data property to the pool byte array I mentioned above:

func RenderToSample():
	var Sample = = NativeObj_IPxtone.RenderToSample()
	Sample.format = AudioStreamSample.FORMAT_16_BITS
	Sample.loop_mode = AudioStreamSample.LOOP_DISABLED
	Sample.loop_begin = 0
	Sample.loop_end = 0
	Sample.mix_rate = SamplesPerSecond
	if NumChannels == 2:
	    Sample.stereo = true
	    Sample.stereo = false
	return Sample

! Note that doing this might be unsafe, as the .data property is not found anywhere in Godot’s documentation.