Search code examples
c++fmod

FMOD play multiple sounds at same time


I needed to play multiple sounds simultaneously, so I tried to initialize the FMOD::System with many channels, but after playing some files it does nothing. When I sleep 1 second, the sound stops with count about 35, with sleep 0.1 second the last count is about 100.

int count = 1;

FMOD::System *system = NULL;
FMOD::System_Create(&system);
system->init(100, FMOD_INIT_NORMAL, 0);

while(true)
{
    FMOD::Sound *sound = NULL;
    system->createSound("test.wav", FMOD_DEFAULT, FMOD_DEFAULT ,&sound);

    FMOD::Channel *channel = NULL;
    FMOD_RESULT result = system->playSound(FMOD_CHANNEL_FREE, sound, false, &channel);

    cout << "count: " << count << ", " << result;
    count++;
    struct timespec ts;
    ts.tv_sec = 1;
    nanosleep(&ts, NULL);
}

When I also write this part into the while loop I also recognized, that the pointer to the FMOD::System changes at the very beginning and remains the same after some seconds.

FMOD::System *system = NULL;
FMOD::System_Create(&system);
system->init(100, FMOD_INIT_NORMAL, 0);

What have I done wrong? It even doesn't use the 100 channels! What can I do to play many sounds synchronously?


Solution

  • The problem was, that I forgot to system->update().
    The code code should look like this:

    int count = 1;
    
    FMOD::System *system = NULL;
    FMOD::System_Create(&system);
    system->init(100, FMOD_INIT_NORMAL, 0);
    
    while(true)
    {
        FMOD::Sound *sound = NULL;
        system->createSound("test.wav", FMOD_DEFAULT, FMOD_DEFAULT ,&sound);
    
        FMOD::Channel *channel = NULL;
        FMOD_RESULT result = system->playSound(FMOD_CHANNEL_FREE, sound, false, &channel);
    
        system->update(); // very important!!!
    
        cout << "count: " << count << ", " << result;
    
        count++;
    
        struct timespec ts;
        ts.tv_sec = 1;
        nanosleep(&ts, NULL);
    }