Skip to content

Instantly share code, notes, and snippets.

@ali1234
Created March 10, 2021 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ali1234/83e9e63d7ff633f6c4d87912596e413f to your computer and use it in GitHub Desktop.
Save ali1234/83e9e63d7ff633f6c4d87912596e413f to your computer and use it in GitHub Desktop.
Wave sound playerback manager for 32Blit
// hpp
#pragma once
#include <cstdint>
#include "32blit.hpp"
enum Sound {
BlockSmash,
NormalLand,
GarbageLand,
Move,
Rotate,
Drop,
};
class SoundMgr {
public:
enum Channel {
Left = 0,
Right = 1,
Misc = 2,
};
static SoundMgr& get(Channel c);
void play(Sound sound);
void wave_callback(blit::AudioChannel &channel);
protected:
uint8_t vol = 0;
SoundMgr(Channel c);
~SoundMgr();
const Channel c;
const int8_t *sample_ptr;
const int8_t *sample_end;
};
// cpp
#include <cstring>
#include "SoundMgr.hpp"
#include "../snd/snd.hpp"
void audio_bouncer(blit::AudioChannel &channel) {
if (channel.user_data) {
((SoundMgr *) (channel.user_data))->wave_callback(channel);
} else {
channel.wave_buffer_callback = nullptr;
memset(channel.wave_buffer, 0, 128);
}
}
SoundMgr::SoundMgr(Channel c) : c(c), sample_ptr(nullptr), sample_end(nullptr) {
blit::channels[c].user_data = this;
blit::channels[c].waveforms = blit::Waveform::WAVE;
blit::channels[c].wave_buffer_callback = &audio_bouncer;
}
SoundMgr::~SoundMgr() {
blit::channels[c].user_data = nullptr;
}
void SoundMgr::wave_callback(blit::AudioChannel &channel)
{
unsigned remaining = sample_end - sample_ptr;
if (remaining > 64) remaining = 64;
for (unsigned n = 0; n < remaining; n++)
channel.wave_buffer[n] = sample_ptr[n]<<vol;
for (unsigned n = remaining; n < 64; n++)
channel.wave_buffer[n] = 0;
sample_ptr += remaining;
if (remaining == 0) {
channel.off();
}
}
void SoundMgr::play(Sound sound) {
switch (sound) {
case Sound::BlockSmash:
vol = 3;
sample_ptr = (int8_t *)block_smash;
sample_end = (int8_t *)block_smash + block_smash_length;
break;
// etc
default:
sample_ptr = nullptr;
sample_end = nullptr;
break;
}
blit::channels[c].trigger_attack();
}
SoundMgr& SoundMgr::get(const Channel c) {
static SoundMgr *sound_mgrs[3];
if (!sound_mgrs[c])
sound_mgrs[c] = new SoundMgr(c);
return *sound_mgrs[c];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment