/
SDLSoundSynthesis.cpp
134 lines (98 loc) · 2.72 KB
/
SDLSoundSynthesis.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
/*
* SDLSoundSynthesis.cpp
*
* Created on: 15.2.2013
* Author: Tomas Ukkonen
*/
#include "SDLSoundSynthesis.h"
#ifdef WINOS
#include <windows.h>
#endif
#include <pthread.h>
#include <sched.h>
SDLSoundSynthesis::SDLSoundSynthesis()
{
SDL_zero(desired);
SDL_zero(snd);
desired.freq = 44100;
//desired.freq = 22050;
desired.format = AUDIO_S16SYS;
desired.channels = 1; // use mono sound for now
desired.samples = 4096;
desired.callback = __sdl_soundsynthesis_mixaudio;
desired.userdata = this;
dev = 0;
}
SDLSoundSynthesis::~SDLSoundSynthesis() {
if(dev != 0){
SDL_CloseAudioDevice(dev);
dev = 0;
}
}
bool SDLSoundSynthesis::play()
{
if(dev == 0){
dev = SDL_OpenAudioDevice(NULL, 0, &desired, &snd,
SDL_AUDIO_ALLOW_FREQUENCY_CHANGE);
}
if(dev == 0){
printf("SDL Error: %s\n", SDL_GetError());
const int numDrivers = SDL_GetNumAudioDrivers();
if(numDrivers > 0)
printf("Number of audio drivers: %d\n", numDrivers);
for(int i=0;i<numDrivers;i++)
printf("Driver %d : %s\n", i, SDL_GetAudioDriver(i));
// prints audio devices
const int numDevices = SDL_GetNumAudioDevices(0);
if(numDevices >= 0)
printf("Number of audio devices: %d\n", numDevices);
for(int i=0;i<numDevices;i++){
printf("Audio device %d: %s\n", i, SDL_GetAudioDeviceName(i, 0));
}
fflush(stdout);
return false;
}
if(snd.format != AUDIO_S16SYS || snd.channels != 1){
if(dev != 0) SDL_CloseAudioDevice(dev);
dev = 0;
return false;
}
if(dev != 0)
SDL_PauseAudioDevice(dev, 0);
return true;
}
bool SDLSoundSynthesis::pause()
{
if(dev != 0)
SDL_PauseAudioDevice(dev, 1);
else
return false;
return true;
}
static bool __sdl__soundsynth_setpriority = false;
void __sdl_soundsynthesis_mixaudio(void* unused,
Uint8* stream, int len)
{
#if 1
if(!__sdl__soundsynth_setpriority){
sched_param sch_params;
int policy = SCHED_FIFO; // SCHED_RR
pthread_getschedparam(pthread_self(), &policy, &sch_params);
policy = SCHED_FIFO;
sch_params.sched_priority = sched_get_priority_max(policy);
if(pthread_setschedparam(pthread_self(),
policy, &sch_params) != 0){
}
#ifdef WINOS
SetThreadPriority(GetCurrentThread(),
THREAD_PRIORITY_HIGHEST);
SetThreadPriority(GetCurrentThread(),
THREAD_PRIORITY_TIME_CRITICAL);
#endif
__sdl__soundsynth_setpriority = true;
}
#endif
SDLSoundSynthesis* s = (SDLSoundSynthesis*)unused;
if(s == NULL) return;
s->synthesize((int16_t*)stream, len/2);
}