Search code examples
csdl-2sdl-mixer

SDL2 Mix_LoadWAV problem. Mix_LoadWAV(path) loads the wav successfully but then frees it automatically


I create a game in C language using SDL2 and I got a problem for 3 days that I couldn't fix, because everything was OK, there was no any problem/bug with my code (I am sure about that), but somehow it just did not work, and finallly I found the problem, so I just wanted to share the answer just in case someone will have the same problem in the future.


Solution

  • When I create a variable like

    Mix_Chunk* sfx = Mix_LoadWAV("./coin.wav");
    

    in the main function (or globally by defining it out of the main function),after assigning to the variable and check if it is null or not, it says it returned the pointer successfully, so it is not null. But when I try to play the sound, (whether in the main function or in the game loop) it just wasn't playing and it was returning null when I check if the sfx variable was null or not. So there was a problem that was freeing the sfx automatically, I tried everything but nothing worked. And finally I just changed the path to

    Mix_Chunk* sfx = Mix_LoadWAV("coin.wav");
    

    and it works now, it doesn't free the sfx until we do it manually. So, just remove the ./ part, I haven't tried if it would be same for a sub-folder path (i.e ./sounds/coin.wav -> sounds/coin.wav), but I just wanted to share the answer because I found nothing on google about this. So I hope this will be helpful for someone who would have the same problem in the future.