I try to make little program with SDL2 and C++. There is a window and button on window. I want to do that when I press first time the button music starts to play. Yeah I made it work.
if((mouseX >= buttonRect.x && mouseX < (buttonRect.x + buttonRect.w)) && (mouseY >= buttonRect.y && mouseY < (buttonRect.y + buttonRect.h))){
if(event.button.button == SDL_BUTTON(SDL_BUTTON_LEFT)){
if(Mix_PlayingMusic() == 0){
Mix_PlayMusic(music, -1);
}
}
}
But I want to make that when button is pressed second time music would pause. And if it will pressed again it resume.
I tried this:
if((mouseX >= buttonRect.x && mouseX < (buttonRect.x + buttonRect.w)) && (mouseY >= buttonRect.y && mouseY < (buttonRect.y + buttonRect.h))){
if(event.button.button == SDL_BUTTON(SDL_BUTTON_LEFT)){
if(Mix_PlayingMusic() == 0){
Mix_PlayMusic(music, -1);
}else{
if(Mix_PausedMusic() == 1){
Mix_ResumeMusic();
}else{
Mix_PauseMusic();
}
}
}
}
But it won't work. When I press the button music starts and stops instantly. If If I hold mouse button down on the button music will play, but if I move mouse it stops.
Mix_PlayMusic returns 0 on success, or -1 on errors. Try defining static variable to follow state of the player;
if((mouseX >= buttonRect.x && mouseX < (buttonRect.x + buttonRect.w)) && (mouseY >= buttonRect.y && mouseY < (buttonRect.y + buttonRect.h))){
static int STATE = 0; // not played
if(event.button.button == SDL_BUTTON(SDL_BUTTON_LEFT)){
if(STATE == 0){
Mix_PlayMusic(music, -1);
STATE = 1; // playing music
}else{
if(STATE == 2){
Mix_ResumeMusic();
} else {
Mix_PauseMusic();
STATE = 2; // paused
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.