-1

I am trying to play a wav file in C++ using Visual Studio. I put file "my.wav" in my project directory and use the code

PlaySound(TEXT("my.wav"), NULL, SND_FILENAME | SND_SYNC);

I hit the play button (or F5 or even Ctrl-F5) and it plays the sound fine.

I open a command prompt and go to Debug/ and run MyApp.exe and when it runs it plays the error chime.

Note: Ideally the sound would be bundled in the exe so I can just distribute the exe and it would work. I tried putting it in an Resource.rc but the code I see in all the examples

PlaySound( (char*)IDR_WAVE1, NULL, SND_RESOURCE | SND_SYNC );

doesn't even compile for me. Complains about IDR_WAVE1 even though that is the name of my resource.

Serve Laurijssen
  • 9,266
  • 5
  • 45
  • 98
  • Isn't `IDR_WAVE1` just an integer identifying a resource? – wilx Apr 05 '16 at 11:12
  • Are you sure you are doing this [how it should be done](https://msdn.microsoft.com/en-us/library/windows/desktop/dd743679(v=vs.85).aspx)? – wilx Apr 05 '16 at 11:17
  • 2
    You are using a relative path (*"my.wav"*). The current working directory set by Visual Studio is different from the current working directory, when launched from a command prompt. Either bundle the WAV as a resource, or use fully qualified paths. – IInspectable Apr 05 '16 at 11:41
  • Link it as a resource. Don't just try to do that, fail, give up, and adopt a much worse solution. Linking files as resources is easy. – David Heffernan Apr 05 '16 at 13:43
  • @wix. I had tried to follow that resource you mention, but ended up with the described behavior. I then found three other examples on the internet (all mostly similar but slightly different) and tried to mimic those, with no better results. So, no, I am quite sure I am not doing this how I should. That's why I put it on Stack Overflow. – Rob Antonucci Apr 07 '16 at 12:42

2 Answers2

0

As I recall it you need to 'link' the resource file with a resource script file ".rc file" in Visual Studio to embed it inside the .exe file. Otherwise you need to load it like @wilx points out.

vlind
  • 629
  • 6
  • 16
0

I'm a little rusty on old school win32 but it was something like this:

include resource.h in your file and use MAKEINTRESOURCE

PlaySound(MAKEINTRESOURCE(IDR_WAVE1), NULL, SND_RESOURCE | SND_SYNC );
Serve Laurijssen
  • 9,266
  • 5
  • 45
  • 98
  • I had tried that already, but tried it again after your answer and realized my mistake. I actually had two resource files (because I'm clueless to Visual Studio) and including resource.h wasn't helping because I needed to include resource1.h. I collapsed my two resource files to one and it works now as a resource. – Rob Antonucci Apr 07 '16 at 12:45
  • Technically, IInspectable is the one who answered by original question of why it doesn't work when run as .exe, but he answered it as a comment and you solved my problem, so marking yours as the correct solution. – Rob Antonucci Apr 07 '16 at 12:47