#include #include #include #include #include #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; }