Search code examples
c++mp3fmod

Why doesn't playSound actually output any sound using FMOD on windows?


FMOD_RESULT result;
FMOD::System *system;

result = FMOD::System_Create(&system);      
if (result != FMOD_OK)
{
    printf("FMOD error! (%d) %s\n", result, FMOD_ErrorString(result));
}

result = system->init(100, FMOD_INIT_NORMAL, 0);    
if (result != FMOD_OK)
{
    printf("FMOD error! (%d) %s\n", result, FMOD_ErrorString(result));
}

FMOD::Sound *sound;
result = system->createSound("01.mp3", FMOD_DEFAULT, 0, &sound);        // FMOD_DEFAULT uses the defaults.  These are the same as FMOD_LOOP_OFF | FMOD_2D | FMOD_HARDWARE.
ERRCHECK(result);

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

I've traced the above code,there is no error/warning, but 01.mp3 isn't played,why?


Solution

  • While the code looks fine to me, note that playSound() is asynchronous. If you're exiting directly afterwards, the sound will never have time to play. E.g.:

    int main() {
        // ...
        sytem->playSound(FMOD_CHANNEL_FREE, sound, false, &channel);
        // playSound() returns directly, program exits without sound being heard
    }
    

    As a quick work-around for testing (and without knowing what your application will be structured like) you could wait for input from the console:

    result = system->playSound(FMOD_CHANNEL_FREE, sound, false, &channel);
    // ...
    std::cout << "Press return to quit." << std::endl;
    std::cin.get();