Creating audio sample from a Table

I am looking to update an audio sample from a table of points, from my research it sounds like this may be possible with C, unfortunately my only experience with C is making ROMS for the GBA. :sweat_smile:

I was able to get it working in LOVE2D, with the love.sound.SoundData:setSample(), but there is no SDK equivalent as far as I know.

My final goal for this is to be able to display images on an oscilloscope through audio, and make games with that functionality, for all 3 people who have the right hardware.

I think this is only possible with the C API for now. Since audio tends to be quite large, my guess is that doing this with Lua might end up being pretty slow on the actual Playdate hardware…

If it helps, in my animation player app I use playdate->sound->sample->newSampleFromData to create a playable audio sample from the animation’s rendered audio, so maybe you’d be able to adapt this:

int sampleRate = 44100; // playdate hardware's audio sample rate
int duration = 100; // duration in seconds
int numSamples = sampleRate * duration;
int dataLen = numSamples * sizeof(int16_t);
// allocate a sample data buffer and make sure it's all cleared to 0
int16_t* data = pd->system->realloc(NULL, dataLen);
memset(data, 0, dataLen);
// create an audio sample from the data buffer
// the data buffer isn't copied, so it *should* be possible to update it on the fly and hear that reflected in the audio
AudioSample* sample = pd->sound->sample->newSampleFromData((uint8_t*)data, kSound16bitMono, sampleRate, dataLen);
// create a sample player with the given sample
SamplePlayer* player = pd->sound->sampleplayer->newPlayer();
pd->sound->sampleplayer->setSample(player, sample);

You should then be able to set individual samples within the audio data with data[sampleIndex] = sampleValue;, or a whole run of samples with memcpy. The audio can be played and stopped with pd->sound->sampleplayer->play(player, 1, 1.0); and pd->sound->sampleplayer->stop(player);

Then when you’re done and want to free up memory:

pd->sound->sampleplayer->stop(player);
pd->sound->sampleplayer->freePlayer(player);
pd->sound->sample->freeSample(sample);
pd->system->realloc(data, 0);

As for doing this from Lua, maybe this can be wrapped into a C extension or something?

3 Likes

This looks like exactly what I’m looking for, I saw playdate->sound->sample->newSampleFromData in the docs but I wasn’t able to get C working anyway.

Ill look into this, I appreciate it! :playdate_heart:

1 Like