Home > front end >  How to use C PlaySound() function with sound from resources?
How to use C PlaySound() function with sound from resources?

Time:12-11

I'm trying to play the song in simple console executable. However after running the .exe the song doesn't play and the windows notification sound appears instead in loop. The resources are created properly (l am using Codeblocks so l can see them in /obj/debug/) so l suppose that's because the PlaySound() path that l set doesn't lead to the right directory.

How to set the path to resources in PlaySound() function? Thank you in advance

play/main.cpp:

#include <iostream>
#include <thread>
#include <windows.h>
#include <mmsystem.h>

void play() {
  PlaySound(TEXT("a18.wav"), NULL, SND_FILENAME|SND_LOOP|SND_ASYNC);
}

int main() {
  std::thread t(play);
  system("pause>>nul");
  t.join();

  return 0;
}

play/song.rc:

song WAVE "/rsrc/a18.wav"

CodePudding user response:

SND_FILENAME is the wrong flag to use when the audio is in a resource. You need to use the SND_RESOURCE flag instead.

The .rc you have shown is assigning a non-numeric ID song to the resource, you need to use that ID to play the resource. There is even an example of this in PlaySound's documentation: Playing WAVE Resources. In comments, you say you tried MAKEINTRESOURCE(IDR_WAVE1) as the resource ID to play, but MAKEINTRESOURCE() works only with numeric IDs.

Also, you are using the SND_ASYNC flag, which means PlaySound() will exit immediately, thus your thread will terminate immediately, making it useless. You don't really need the thread at all, unless you remove the SND_ASYNC flag.

Try this instead:

#include <windows.h>
#include <mmsystem.h>
#include <cstdlib>

int main() {
  PlaySound(TEXT("song"), GetModuleHandle(NULL), SND_RESOURCE|SND_LOOP|SND_ASYNC);
  std::system("pause>>nul");
  PlaySound(NULL, NULL, 0);

  return 0;
}

Alternatively:

#include <thread>
#include <atomic>
#include <cstdlib>
#include <windows.h>
#include <mmsystem.h>

std::atomic_bool stop(false);

void play() {
  while (!stop.load()) {
    PlaySound(TEXT("song"), GetModuleHandle(NULL), SND_RESOURCE);
  }
}

int main() {
  std::thread t(play);
  std::system("pause>>nul");
  stop.store(true);
  t.join();

  return 0;
}
  • Related