Playing sounds

When I play a wav file sound with this code:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <windows.h>
//I added a library called mmsystem.h

using namespace std;

int main()
{
    PlaySound("a.wav",NULL,SND_FILENAME);
    return 0;
}


it plays the alarm sound(/a), instead of my file. There are no errors, and it compiles fine. Is anything wrong with the code? How can I get it to work? Thanks!
I tried lots of ways, but none of them worked.
@BobTheZealotIsEpic

Try this then. And make sure that 'a.wav' is in the same directory as this program, or change the name to point to where it's located.

IE: std::wstring soundfile(L"C:\\Temp\\a.wav");

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// PlaySound.cpp : main project file.

#include <iostream>
#include <windows.h>
#include <string>

#pragma comment(lib, "winmm.lib")

int main()
{
 std::wstring soundfile(L"a.wav");
 PlaySound(soundfile.c_str(), NULL, SND_ASYNC);
 Sleep(2500);

 std::cout << "Press any key to close program.." << std::endl;
 getchar();
 return 0;
}
Last edited on
@whitenite1

Does the same directory mean I'm supposed to put the wav file in the project folder?
@whitenite1

How should I change the name to point to where it's located?
@BobTheZealotIsEpic

Yep. Unless you want to specify its location. Otherwise, the project directory is the only place your program will look for it.
Ok, thanks. I will do that.
@whitenite1

When I compile your program, it has an error on line 12:

error: cannot convert 'const wchar_t*' to 'LPCSTR {aka const char*}' for argument '1' to 'BOOL PlaySoundA(LPCSTR, HMODULE, DWORD)'
BobTheZealotIsEpic

When I create a program in Visual C++ 12, I start it off as a CLR Console application. I don't know if that makes a difference or not. But then, it compiles and runs, so..
Otherwise, I'm at a loss for an answer. Maybe someone wiser can offer a solution. sorry..
According to MSDN:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa383751(v=vs.85).aspx

LPCSTR is a pointer to a null-terminated string of constant ANSI (8-bit) characters, which is like const char* (and in the error bob posted, it is the same on his compiler).

The L prefix makes the string literal a string of wide characters, so you are essentially doing something akin to:
1
2
3
const wchar_t* wc_str = L"Hello world!";

const char* c_str = wc_str;

http://ideone.com/KXKlPO

I think it'll be okay if you don't use the L prefix (or wide characters in general) in this case .

Edit:
Fixed example.
Last edited on
I don't get what I'm supposed to do.
Trolling?

Because you made some pointless posts in your other pointless topic, I am not going to apologise if you think I am giving you a hard time.
how is you Hi Script coming along BobTheZealotIsEpic ?
What is a
Hi Script
?
Last edited on
Topic archived. No new replies allowed.