#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 Button", 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 *music = loadMusic("s1.wav");
if (music == NULL) {
fprintf(stderr, "Couldn't load music\n");
return 1;
}
SDL_Event event;
SDL_Rect buttonRect = {200, 500, 100, 320};
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;
if (mouseX >= buttonRect.x && mouseX <= buttonRect.x + buttonRect.w &&
mouseY >= buttonRect.y && mouseY <= buttonRect.y + buttonRect.h) {
Mix_PlayMusic(music, 0);
}
}
}
if (event.type == SDL_QUIT) {
break;
}
SDL_RenderClear(renderer);
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_RenderFillRect(renderer, &buttonRect);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderDrawRect(renderer, &buttonRect);
SDL_RenderPresent(renderer);
}
Mix_FreeMusic(music);
Mix_CloseAudio();
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}