-
Notifications
You must be signed in to change notification settings - Fork 0
/
bytebeat-player.cpp
89 lines (64 loc) · 1.78 KB
/
bytebeat-player.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
#include <stdio.h>
#include <stdint.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_audio.h>
typedef uint32_t u32;
typedef uint16_t u16;
typedef uint8_t u8;
uint32_t audioSample = 0;
uint32_t lastSample = 0;
uint32_t lastResult = 0;
void audioCallback(void* userdata,unsigned char* stream,int len);
uint32_t byteBeat(uint32_t sample);
uint32_t divnz(uint32_t a,uint32_t b);
uint32_t modnz(uint32_t a,uint32_t b);
int main(int argc,char* argv[]) {
SDL_AudioSpec want;
SDL_AudioSpec have;
SDL_AudioDeviceID dev;
SDL_Init(SDL_INIT_AUDIO);
SDL_zero(want);
want.freq = 44100;
want.format = AUDIO_S16SYS;
want.channels = 1;
want.samples = 4096;
want.callback = audioCallback;
want.userdata = (void*)&audioSample;
dev = SDL_OpenAudioDevice(NULL,0,&want,&have,0);
if (dev == 0) {
SDL_Log("Failed to open audio: %s",SDL_GetError());
return 2;
}
fprintf(stderr,"playing... ");
SDL_PauseAudioDevice(dev,0);
SDL_Delay(55000);
fprintf(stderr,"\n");
SDL_PauseAudioDevice(dev,1);
SDL_CloseAudioDevice(dev);
return 0;
} // main()
void audioCallback(void* userdata,unsigned char* stream,int len) {
uint32_t* samplePtr = (uint32_t*)userdata;
for (int i = 0; i < len; i += 2) {
uint32_t sample = *samplePtr / (44100 / FREQ);
uint32_t result;
if (sample == lastSample) {
result = lastResult;
} else {
result = ( byteBeat(sample) & 0xFF ) * VOLUME_MUL;
lastSample = sample;
lastResult = result;
}
uint16_t* store = (uint16_t*)&stream[i];
*store = result;
(*samplePtr)++;
} // for stream
} // audioCallback()
inline uint32_t divnz(uint32_t a,uint32_t b) {
if (b == 0) return a;
return a / b;
} // divnz()
inline uint32_t modnz(uint32_t a,uint32_t b) {
if (b == 0) return a;
return a % b;
} // modnz()