Hi,
I don’t know if this is the right place to ask, but I’m trying to
accompany my game with sound right now. I wrote a static SoundPlayer class
(I know static is bad, but I’m just learning right now) as a wrapper
around SDL_mix. It looks like this:
Header File:
#ifndef SOUNDPLAYER_H_INCLUDED
#define SOUNDPLAYER_H_INCLUDED
#include <SDL_mixer.h>
class SoundPlayer
{
public:
static void playSound(int id);
static void playMusic(int id);
static void closeMix();
private:
static Mix_Chunk* sound;
static Mix_Chunk* music;
static int channel;
static int musicChannel;
static bool eating;
};
#endif // SOUNDPLAYER_H_INCLUDED
Source file:
#include “soundplayer.h”
Mix_Chunk* SoundPlayer::sound;
Mix_Chunk* SoundPlayer::music;
int SoundPlayer::channel;
int SoundPlayer::musicChannel;
bool SoundPlayer::eating = false;
void SoundPlayer::playMusic(int id)
{
Mix_FreeChunk(music);
switch (id)
{
case 1 : sound = Mix_LoadWAV("music/stage1.ogg"); break;
default:
break;
}
if(music == NULL)
fprintf(stderr, "Unable to load WAV file: %s\n", Mix_GetError());
musicChannel = Mix_PlayChannel(1, sound, 0);
}
void SoundPlayer::playSound(int id)
{
if (Mix_Playing(channel) && !eating) return;
if (id == 1) eating = true;
else eating = false;
Mix_FreeChunk(sound);
switch (id)
{
case 1 : sound = Mix_LoadWAV("sounds/Eat.ogg"); break;
case 2 : sound = Mix_LoadWAV("sounds/1Up.ogg"); break;
case 3 : sound = Mix_LoadWAV("sounds/Bite.ogg"); break;
default:
break;
}
if(sound == NULL)
fprintf(stderr, "Unable to load WAV file: %s\n", Mix_GetError());
channel = Mix_PlayChannel(2, sound, 0);
}
void SoundPlayer::closeMix()
{
Mix_FreeChunk(music);
Mix_FreeChunk(sound);
Mix_CloseAudio();
}
Now what happens it this: When I call playMusic(1), the file
music/stage1.ogg is loaded and plays and expected. However, once I call
playSound(1), the sound for eating an egg is indeed played, but the music
just stops and doesn’t continue playing, even after the sound effect is
over.
I checked that SDL_mix uses the right channels by placing rather harsh
control statements (i.e. “if (channel != 2) exit(channel)”) which didn’t
trigger. So it uses channel 1 for music and channel 2 for sound.
Why does this happen? The whole point of using SDL_mix is being able to
play different sounds at the same time.
thanks,
Andreas