-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSoundEngine.cpp
72 lines (60 loc) · 2.1 KB
/
SoundEngine.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
//
// Created by vincenzo on 22/10/22.
//
#include "SoundEngine.h"
SoundEngine* SoundEngine::instance= nullptr;
SoundEngine::SoundEngine() {
if(SDL_Init(SDL_INIT_AUDIO | SDL_INIT_TIMER) != 0){
SDL_Log("Unable to initialize SDL AudioSystem: %s", SDL_GetError());
exit(1);
}
SDL_memset(&want,0,sizeof(want));
want.freq=samplePerSecond;
want.format=audioFormat;
want.channels=audioChannels;
want.samples=sampleBufferSize;
want.callback= SoundEngine::forwardCallback;
want.userdata= this;
audioDevice = SDL_OpenAudioDevice(nullptr,0,&want,&have,
SDL_AUDIO_ALLOW_FORMAT_CHANGE);
}
SoundEngine::~SoundEngine() {
SDL_CloseAudioDevice(audioDevice);
}
void SoundEngine::startPlaying() const {
SDL_PauseAudioDevice(audioDevice,0);//SDL start calling the callback function this result in sound.
}
void SoundEngine::stopPlaying() const {
SDL_PauseAudioDevice(audioDevice,1);//SDL stop calling the callback function this result in silence.
}
void SoundEngine::addSynth(WaveTableSynth *s,float wantedFreq) {
s->generateTable(synthTableSize);
s->setWantedFreq(wantedFreq);
synthesizers.push_front(s);
}
void SoundEngine::removeSynth(WaveTableSynth *s) {
synthesizers.remove(s);
}
void SoundEngine::forwardCallback(void *userdata, Uint8 *stream, int len) {
//forward audioCallback to audioCallback memberFunction
static_cast<SoundEngine*>(userdata)->audioCallback(stream,len);
}
void SoundEngine::audioCallback(Uint8 *stream, int len) {
auto* signedStream=reinterpret_cast<int16_t *>(stream);
uint32_t samples = len / sizeof(int16_t);
for (int i = 0; i < samples; i+=2) {
float left=0;
float right=0;
for (auto &synth :synthesizers) {
synth->renderAudioSample(left,right);
}
signedStream[i]=(int16_t)(32767.0f * left / (float)synthesizers.size());
signedStream[i+1]=(int16_t)(32767.0f * left / (float)synthesizers.size());;
}
}
SoundEngine *SoundEngine::getInstance() {
if(!instance){
instance= new SoundEngine;
}
return instance;
}