summaryrefslogtreecommitdiff
path: root/main.c
blob: 0932d7d7a21730c139fd642fdf313af97c8a9351 (plain)
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
#include <SDL2/SDL.h>
#include <SDL2/SDL_events.h>
#include <SDL2/SDL_mixer.h>
#include <SDL2/SDL_timer.h>
#include <stdio.h>

#define NUM_CLAPS 10

int main(int argc, char **argv) {
	(void)argc, (void)argv;

	/* Initialize SDL and SDL_mixer. */
	if (SDL_Init(SDL_INIT_AUDIO)) {
		fprintf(stderr, "%s\n", SDL_GetError());
		return 1;
	}
	if (atexit(SDL_Quit)) {
		perror("atexit(SDL_Quit)");
		SDL_Quit();
		return 1;
	}
	if (Mix_Init(MIX_INIT_FLAC) != MIX_INIT_FLAC) {
		fprintf(stderr, "%s\n", Mix_GetError());
		return 1;
	}
	if (atexit(Mix_Quit)) {
		perror("atexit(Mix_Quit)");
		Mix_Quit();
		return 1;
	}

	/* Open audio device. */
	if (Mix_OpenAudio(48000, AUDIO_F32SYS, 2, 4096)) {
		fprintf(stderr, "%s\n", Mix_GetError());
		return 1;
	}
	if (atexit(Mix_CloseAudio)) {
		perror("atexit(Mix_CloseAudio)");
		Mix_CloseAudio();
		return 1;
	}

	/* Allocate mixing channels to play more than 8 sounds in parallel. */
	if (Mix_AllocateChannels(69) != 69)
		fprintf(stderr, "%s\n", Mix_GetError());

	Mix_Chunk *claps[NUM_CLAPS];
	for (int i = 0; i < NUM_CLAPS; i++) {
		claps[i] = Mix_LoadWAV("clap.wav");
		if (claps[i] == NULL) {
			fprintf(stderr, "%s\n", Mix_GetError());
			for (int k = 0; k < i; k++)
				Mix_FreeChunk(claps[k]);
			break;
		}
	}

	/* Main loop. */
	int loop = 1;
	Uint64 was_ticks = SDL_GetTicks64();
	int clap_id = 0;
	while (loop) {
		/* Handle SDL_QUIT event (likely Ctrl-C). */
		SDL_Event e;
		while (SDL_PollEvent(&e))
			if (e.type == SDL_QUIT)
				loop = 0;

		const Uint64 ticks = SDL_GetTicks64();
		if (ticks == was_ticks)
			continue;


		/* Play clap sound every 200 milliseconds. */
		if (ticks >= was_ticks + 200) {
			was_ticks = ticks;
			Mix_PlayChannel(-1, claps[clap_id], 0);
			clap_id = (clap_id + 1) % NUM_CLAPS;
		}
	}

	/* Most of cleanup is handled by previous atexit calls, although we
	 * still need to manually free audio chunks. */
	for (int i = 0; i < NUM_CLAPS; i++)
		Mix_FreeChunk(claps[i]);
	return 0;
}