Hello. I’m trying to write a little one-off program. I use C++ and SDL library. Those details don’t matter as I am having problems with writing the logic.
It should do this:
- Start playing the first song & begin iterating through an array of image files, displaying each one and waiting n-milliseconds before displaying the next one
- Is the first song done? Play the second one
- Quit, when the user presses X or ALT-F4 on keyboard.
So, the target is to do this: plays 2 songs, iterates over pictures while the songs are playing (sort of a slideshow), quits only when the user closes it.
I am having a problem with organizing the logic.
The main loop iterates, only after the n-milliseconds that I give to the function SDL_Delay(n) has passed. This causes the problem that, when the user wants to quit the program, it does not quit until the next iteration of the loop. It “freezes” there until the next iteration, doesn’t quit immediately.
I tried to create a function that takes a song filename argument and plays it then returns. This works alright.
My problem is with the delay after displaying each image: I can’t figure a way to do both: Quit immediately when the user closes the window && delay n-milliseconds between each picture. Even if I wrote a function that takes image filename argument and displays it and delays n-milliseconds, main() is still stuck waiting for that function to return, and dealing with a quit event is still stuck along with that delay.
I wonder, if it is possible to have two loops run along parallely? Or if the logic could be organized better?
Please help.
This is the main file. The other defintions are in other files and work as I intend them to do.
Code:
int main(int argc, char* argv[])
{
vector<SDL_Surface*> surfaces(26, NULL);
SDL_Event e;
bool quit = false;
bool first = false; // Set to true when the first song has been played
bool second = false; // Set to true when the second song has been played
vector<Mix_Music*> m(2, NULL);
// Initialize SDL facilities
if (!init())
{
cout << "Initialization failed" << endl;
return 1;
}
else
{
unsigned int i = 0;
while (!quit)
{
// Start first song
if ((!Mix_PlayingMusic() && !first) && !second)
{
first = true;
m[0] = loadMusic(songs[0].c_str());
Mix_PlayMusic(m[0], 1);
}
// Start second song
if ((!Mix_PlayingMusic() && first) && !second)
{
second = true;
m[1] = loadMusic(songs[1].c_str());
Mix_PlayMusic(m[1], 1);
}
// Image display
if (i < images.size());
{
if (!loadImage(images[i].c_str(), surfaces[i]))
{
cout << "Failed to load image\n";
}
else
{
SDL_Rect stretchRect;
stretchRect.x = 0;
stretchRect.y = 0;
stretchRect.w = SCREEN_WIDTH;
stretchRect.h = SCREEN_HEIGHT;
SDL_BlitScaled(surfaces[i], NULL,
gScreenSurface, &stretchRect);
SDL_UpdateWindowSurface(gWindow);
SDL_Delay(15000);
}
++i;
}
// Check if user wants to quit
while (SDL_PollEvent(&e) != 0)
{
if (e.type == SDL_QUIT)
quit = true;
}
}
}
// Cleanup
Mix_FreeMusic(m[1]);
Mix_FreeMusic(m[0]);
close(surfaces);
return 0;
}
[/code]