locked
Play a sound in C++ RRS feed

  • Question

  • Hi, I have a simple c++ program.  I want to know how to add code that will play a sound file from a given path.  Any help would be appreciated, thanks.  None of the MSDN examples seem to have code for c++ and I read somewhere that c++ does not natively support playing a sound without adding an extension.  But, I read there is a work around.  Could someone please help, thanks.
    Thursday, July 7, 2011 11:24 PM

Answers

  • You are compiling with Unicode enabled.
    Therefore PlaySound maps to PlaySoundW
    which needs wchar_t args.

    Note also that you must double backslashes in your
    code, as it's the escape character.

    You will also have to specify winmm.lib for the linker
    or you will get link errors.

    #include "stdafx.h"
    #include <windows.h>
    #pragma comment(lib, "winmm.lib")

    int _tmain(int argc, _TCHAR* argv[])
    {
      PlaySound(_T("C:\\Users\\Jesse\\Desktop\\beep-07.WAV"),
        NULL, SND_ASYNC);
      return 0;
    }

    - Wayne
    • Marked as answer by Rob Pan Thursday, July 14, 2011 9:02 AM
    Friday, July 8, 2011 1:52 AM

All replies

  • If you don't need asynchronous playback, `PlaySound' is quite easy to use and comes with examples.

    • Proposed as answer by SA PRE Monday, July 11, 2011 8:17 AM
    Thursday, July 7, 2011 11:34 PM
  • Thanks! :)
    Friday, July 8, 2011 1:05 AM
  • I added this line of code to my program:

    PlaySound(

    "C:\Users\Jesse\Desktop\beep-07.WAV", NULL, SND_ASYNC);

    And get the following error:

    error: argument of type "const char*" is incompatible with parameter of type "LPCWSTR"

    Any idea why this is?  Just in case the problem isn't related to c++, I am using a real-time extension to windows called RTX.

    Friday, July 8, 2011 1:18 AM
  • You are compiling with Unicode enabled.
    Therefore PlaySound maps to PlaySoundW
    which needs wchar_t args.

    Note also that you must double backslashes in your
    code, as it's the escape character.

    You will also have to specify winmm.lib for the linker
    or you will get link errors.

    #include "stdafx.h"
    #include <windows.h>
    #pragma comment(lib, "winmm.lib")

    int _tmain(int argc, _TCHAR* argv[])
    {
      PlaySound(_T("C:\\Users\\Jesse\\Desktop\\beep-07.WAV"),
        NULL, SND_ASYNC);
      return 0;
    }

    - Wayne
    • Marked as answer by Rob Pan Thursday, July 14, 2011 9:02 AM
    Friday, July 8, 2011 1:52 AM
  • Great thanks for the info.  C++ is a little complicated for me, I think I will stick to VB .NET.
    Friday, July 8, 2011 4:32 AM