Search code examples
c++irrklang

irrKlang get ISound* from play2D()


I'm trying to load a sound with irrKlang library and it works fine at playing, but I want to get PlayLength() and PlayPosition() properties but program crashes when done. This is what I do:

#define ResX "res.mod"

irrklang::ISoundEngine* se = irrklang::createIrrKlangDevice();
if( !se->isCurrentlyPlaying( ResX ) ){
     irrklang::ISound *s = se->play2D( ResX, false, false, false );
     while( s->getPlayPosition() < s->getPlayLength() ) //Do something
}

When I do s->getPlayPosition() or s->getPlayLength() program crashes

I put some clarificaction here first: I cant use while( se->isCurrentlyPlaying( ResX ) ) because isCurrentlyPlaying() doesn't return 0 when media stopped playing sometimes.


Solution

  • You aren't checking the return value of play2D to see if it is a valid pointer or not (and it isn't)

    Your code says:

    irrklang::ISound *s = se->play2D( ResX, false, false, false );
    

    According to the docs:

    Only returns a pointer to an ISound if the parameters 'track', 'startPaused' or 'enableSoundEffects' have been set to true. Note: if this method returns an ISound as result, you HAVE to call ISound::drop() after you don't need the ISound interface anymore. Otherwise this will cause memory waste. This method also may return 0 altough 'track', 'startPaused' or 'enableSoundEffects' have been set to true, if the sound could not be played.

    So, you pass false for 'track', 'startPaused' and 'enableSoundEffects' and the docs specifically say that a valid pointer will not be returned unless one of them is true.