2

I am making a simple snake game with SFML and am currently trying to add a sound that plays whenever the snake "eats" one of the dots. So I downloaded a sound file and put it in my project directory and added this to my code:

sf::SoundBuffer buffer;
buffer.loadFromFile("Crunch.wav")
sf::Sound crunch;
crunch.setBuffer(buffer);
if (snake.isTouching(food))
{
    crunch.play();
}

When I run the game from Visual Studio it works fine. But I like to put my finished games on my desktop, so I went into my Debug folder, found my .exe file, made a shortcut and placed it on my desktop. But whenever I try to run the program with the desktop shortcut, the message "Failed to open sound file 'Crunch.wav' (couldn't open stream)" shows up on the output window. Does anyone know what is causing this? The program runs as it's supposed to when I run it from VS. Thanks in advance.

4
  • 1
    Seems like when it's launched from the desktop the current directory is not the program's directory. Commented Jul 23, 2020 at 22:14
  • @SamVarshavchik What is the current directory then? The desktop?
    – JensB
    Commented Jul 23, 2020 at 22:17
  • 2
    @JensB It is whatever path is specified inside the shortcut you created. Go into the shortcut's Properties and set the "Start in" field to whatever path you want. Otherwise, you should just update your code to use an absolute path instead of a relative path when loading the sound file. The program can determine the path to the folder it is located in by examining the path portion of the filename reported by argv[0] in main(), or by GetModuleFileName(NULL) Commented Jul 23, 2020 at 22:24
  • 1
    Related: stackoverflow.com/questions/875249/how-to-get-current-directory
    – Eljay
    Commented Jul 23, 2020 at 22:36

1 Answer 1

2

loadFromFile() looks in the current directory, when you build and run in visual studio the directory is ProjectName\ProjectName by default, in this case it seems you have Crunch.wav in the ProjectName\ProjectName folder alongside the .vcxproj file, so you should make sure to keep Crunch.wav with the .exe in the same way you have it in the project folder, in this case copying Crunch.wav to the same location as the .exe

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.