#include #include #include "SDL.h" #include "SDL_mixer.h" #include "SDL_thread.h" Mix_Chunk *phaser = NULL; Mix_Music *music = NULL; int phaserChannel = -1; void handleKey(SDL_KeyboardEvent key); void musicDone(); /*This function polls every 20 ms for new SDL_Events. If it finds such events, it determines type and has a behaviour for different SDL_Keys. It can be called by SDL_Quit or other events.*/ int main(void) { SDL_Surface *screen; SDL_Event event; int done = 0, bits = 0, audio_rate = 44100, audio_channels = 2, audio_buffers = 4096, volume = SDL_MIX_MAXVOLUME; Uint16 audio_format = AUDIO_S16; // Opening the sound and graphic card SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO); if(Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers)) { printf("Unable to open audio!\n"); exit(1); } // Print out some info on the audio device and stream Mix_QuerySpec(&audio_rate, &audio_format, &audio_channels); bits=audio_format&0xFF; printf("Opened audio at %d Hz %d bit %s, %d bytes audio buffer\n", audio_rate, bits, audio_channels>1?"stereo":"mono", audio_buffers ); // phaser = Mix_LoadWAV("phaser.wav"); screen = SDL_SetVideoMode(1024,768,0,SDL_FULLSCREEN|SDL_ANYFORMAT|SDL_HWSURFACE|SDL_DOUBLEBUF); SDL_WM_SetCaption("mixer4 - SDL_mixer demo","mixer4"); SDL_ShowCursor(SDL_DISABLE); while(!done) { while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_QUIT: done = 1; break; case SDL_KEYDOWN: switch(event.key.keysym.sym){ // Escape and q exit the loop case SDLK_ESCAPE: done = 1; break; case SDLK_q: done = 1; break; // Restart the music case SDLK_r: Mix_RewindMusic(); break; // For future implementation with a mp3 -> fast forward and backwards case SDLK_LEFT: switch(Mix_GetMusicType(NULL)) { case MUS_MP3: Mix_SetMusicPosition(-5); break; default: printf("Cannot turn back this type of music\n"); break; } break; case SDLK_RIGHT: switch(Mix_GetMusicType(NULL)) { case MUS_MP3: Mix_SetMusicPosition(+5); break; default: printf("cannot forward this type of music\n"); break; } break; // Up and down serve as volume control case SDLK_UP: volume=(volume+1)<<1; if(volume>SDL_MIX_MAXVOLUME) volume=SDL_MIX_MAXVOLUME; Mix_VolumeMusic(volume); break; case SDLK_DOWN: volume>>=1; Mix_VolumeMusic(volume); break; // Stops the music and continues the music case SDLK_SPACE: if(Mix_PausedMusic()) Mix_ResumeMusic(); else Mix_PauseMusic(); break; // Phaser case SDLK_p: if(event.key.type == SDL_KEYDOWN) { if(phaserChannel < 0) { phaserChannel = Mix_PlayChannel(-1, phaser, -1); } else { Mix_HaltChannel(phaserChannel); phaserChannel = -1; } } break; // Music case SDLK_m: if(event.key.state == SDL_PRESSED) { if(music == NULL) { music = Mix_LoadMUS("music.ogg"); Mix_PlayMusic(music, 0); Mix_HookMusicFinished(musicDone); } else { Mix_HaltMusic(); Mix_FreeMusic(music); music = NULL; } } break; default: break; } } SDL_Delay(30); } } Mix_CloseAudio(); SDL_Quit(); } void musicDone() { Mix_HaltMusic(); Mix_FreeMusic(music); music = NULL; }