Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 26th, 2012  |  syntax: None  |  size: 1.81 KB  |  hits: 9  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #include <SDL/SDL_mixer.h>
  2. #include <SDL/SDL.h>
  3.  
  4. typedef enum {
  5.         SOUND_NONE = 0, // Just to be safe
  6.         SOUND_YAY,
  7.         SOUND_WOOT
  8. } soundTrack;
  9.  
  10. #define NUM_CHUNKS 3
  11. #define SOUND_PANNINGSCOPE 0.5
  12.  
  13. Mix_Chunk* chunks[NUM_CHUNKS];
  14. unsigned char enabled = 0;
  15.  
  16. void initSound(void){
  17.         SDL_RWops* handle;
  18.        
  19.         if(Mix_OpenAudio(SOUND_FREQUENCY, AUDIO_S16SYS, 2, SOUND_CHUNKSIZE) == -1){
  20.                 ;// Give the user a warning that sound isn't available
  21.                 return;
  22.         }
  23.         enabled = 1;
  24.        
  25.         chunks[0] = NULL;
  26.        
  27.         handle = SDL_RWFromFile("path/to/sound.wav", "r");
  28.         if(handle == NULL) ;// Throw an error that the file couldn't be loaded
  29.         chunks[1] = Mix_LoadWAV_RW(handle, 0);
  30.         if(chunks[1] == NULL) ;// Throw an error that the file couldn't be read
  31.         SDL_RWclose(handle);
  32.        
  33.         handle = SDL_RWFromFile("path/to/anothersound.wav", "r");
  34.         if(handle == NULL) ;// Throw an error that the file couldn't be loaded
  35.         chunks[2] = Mix_LoadWAV_RW(handle, 0);
  36.         if(chunks[2] == NULL) ;// Throw an error that the file couldn't be read
  37.         SDL_RWclose(handle);
  38. }
  39.  
  40. void cleanupSound(void){
  41.         int i;
  42.        
  43.         if(enabled == 0) return;
  44.         Mix_HaltChannel(-1);
  45.         for(i = 1; i < NUM_CHUNKS; ++i){
  46.                 Mix_FreeChunk(chunks[i]);
  47.         }
  48.         Mix_CloseAudio();
  49. }
  50.  
  51. void playSound(soundTrack track){
  52.         int channel;
  53.        
  54.         if(enabled == 0) return;
  55.         channel = Mix_PlayChannel(-1, chunks[track], 0);
  56.         Mix_SetPanning(channel, 255, 255); // Resets the panning in case it was changed on this channel
  57. }
  58.  
  59. void playSoundPan(soundTrack track, int panning){
  60.         int channel;
  61.         float realPanning;
  62.        
  63.         if(enabled == 0) return;
  64.         realPanning = panning;
  65.         realPanning -= 255.0/2;
  66.         realPanning *= SOUND_PANNINGSCOPE;
  67.         realPanning += 255.0/2;
  68.        
  69.         channel = Mix_PlayChannel(-1, chunks[track], 0);
  70.         Mix_SetPanning(channel, 255.0-realPanning, realPanning); // Panned sound is about 50% more silent
  71. }