sdl mixer program. need help!

Apr 17, 2012 at 8:43am
I'm new to the SDL libraries. I have got all the header files installed. The program runs BUT it does not show up "hello!". Neither does it play scratch.wav when i press 1.
All it does is show up a black screen that stays there indefinitely.




#include<iostream.h>
#include "SDL/SDL.h"
#include<SDL/SDL_image.h>
#include<SDL/SDL_ttf.h>

#include "SDL/SDL_mixer.h"
#include <string>

int main( int argc, char* args[] )
{SDL_Init( SDL_INIT_EVERYTHING );

SDL_Event event;



Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 2, 4096 );
Mix_Chunk *scratch = NULL;
cout<<"hello!";
bool quit =false;
while(quit==false)
{



while( SDL_PollEvent( &event ) &&event.type == SDL_KEYDOWN)
{
if(event.key.keysym.sym == SDLK_1)
scratch = Mix_LoadWAV( "scratch.wav" );

else if (event.key.keysym.sym == SDLK_0)
quit=true;

}

}
Mix_PlayChannel( -1, scratch, 0 );
Mix_FreeChunk( scratch );
Mix_CloseAudio();
SDL_Quit();

}
Apr 17, 2012 at 10:24am
To receive key events you have to first create a new window with SDL_SetVideoMode.

Don't load the scratch sound inside the loop. It causes a memory leak because you only free the most recently loaded sound. You better load it before the loops.

You are not starting to play the sound until after the loops. That means you have to press 0 to make the sound play but it will not have much time to play because the program ends right after. The call to Mix_PlayChannel should probably be where you now call Mix_LoadWAV.

You might also want to check if the function calls succeeded or not. Mix_OpenAudio returns -1 on failure and Mix_LoadWAV returns a null pointer on failure.

On windows, SDL for some reason redirects all printed text to files called stdout.txt and stderr.txt. The files are automatically removed when the program terminates.
Last edited on Apr 17, 2012 at 10:29am
Apr 17, 2012 at 1:15pm
Thanxxxxxx
That really helped.

How do i recover lost memory that goes into memory leaks.
Last edited on Apr 17, 2012 at 1:16pm
Apr 17, 2012 at 3:12pm
You should make sure that you don't lose memory in the first place. The problem here was that a new Mix_Chunk object is created each time you press 1 so the program will need more and more memory. I already mentioned that the solution here is to only load it once before the loop and use the same Mix_Chunk through the whole program.

Topic archived. No new replies allowed.