#include <stdio.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_mixer.h>
// Function for loading music to Mix_Music
static Mix_Music *loadMusic(const char *path) {
Mix_Music *music = Mix_LoadMUS(path);
if (music == NULL) {
fprintf(stderr, “Mix_LoadMUS Error: %s\n”, Mix_GetError());
return NULL;
}
return music;
}
int main(int argc, char *argv[]) {
if (SDL_Init(SDL_INIT_EVERYTHING)!= 0) {
fprintf(stderr, “SDL_Init Error: %s\n”, SDL_GetError());
return 1;
}
SDL_Window *window = SDL_CreateWindow("Hello SDL2-mixer with Buttons", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 220, 280, 0);
if (window == NULL) {
fprintf(stderr, "SDL_CreateWindow Error: %s\n", SDL_GetError());
return 1;
}
SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, 0);
if (renderer == NULL) {
fprintf(stderr, "SDL_CreateRenderer Error: %s\n", SDL_GetError());
return 1;
}
if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 4096) == -1) {
fprintf(stderr, "Mix_OpenAudio Error: %s\n", Mix_GetError());
return 1;
}
Mix_Music *musics[6];
musics[0] = loadMusic("s1.wav");
musics[1] = loadMusic("s2.wav");
musics[2] = loadMusic("s3.wav");
musics[3] = loadMusic("s4.wav");
musics[4] = loadMusic("s5.wav");
musics[5] = loadMusic("s6.wav");
SDL_Rect buttonRects[6];
buttonRects[0].x = 60;
buttonRects[0].y = 320;
buttonRects[0].w = 80;
buttonRects[0].h = 300;
buttonRects[1].x = 160;
buttonRects[1].y = 320;
buttonRects[1].w = 80;
buttonRects[1].h = 300;
buttonRects[2].x = 260;
buttonRects[2].y = 320;
buttonRects[2].w = 80;
buttonRects[2].h = 300;
buttonRects[3].x = 360;
buttonRects[3].y = 320;
buttonRects[3].w = 80;
buttonRects[3].h = 300;
buttonRects[4].x = 460;
buttonRects[4].y = 320;
buttonRects[4].w = 80;
buttonRects[4].h = 300;
buttonRects[5].x = 560;
buttonRects[5].y = 320;
buttonRects[5].w = 80;
buttonRects[5].h = 300;
SDL_Event event;
while (1) {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
break;
} else if (event.type == SDL_MOUSEBUTTONDOWN) {
int mouseX = event.button.x;
int mouseY = event.button.y;
for (int i = 0; i < 6; i++) {
if (mouseX >= buttonRects[i].x && mouseX <= buttonRects[i].x + buttonRects[i].w &&
mouseY >= buttonRects[i].y && mouseY <= buttonRects[i].y + buttonRects[i].h) {
if (musics[i]!= NULL) {
Mix_PlayMusic(musics[i], 0);
}
}
}
}
}
if (event.type == SDL_QUIT) {
break;
}
SDL_RenderClear(renderer);
for (int i = 0; i < 6; i++) {
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_RenderFillRect(renderer, &buttonRects[i]);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderDrawRect(renderer, &buttonRects[i]);
}
SDL_RenderPresent(renderer);
}
for (int i = 0; i < 6; i++) {
if (musics[i]!= NULL) {
Mix_FreeMusic(musics[i]);
}
}
Mix_CloseAudio();
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}