Reputation: 1
I'm trying to create a program that plays different sounds when you press different keys. I was planning to take the char key , add the string ".wav" and input that new string called "sound" into the line:
PlaySound(TEXT(sound), NULL, SND_FILENAME | SND_ASYNC);
The code does not compile and gives the error "identifier 'Lsound' is undefined" I've tried replacing "TEXT" with "string" but it gives the error message "no suitable conversion function from 'std::string' to 'LPCWSRT' exists".
Any help with a solution would be greatly appreciated.
#include <iostream>
#include <Windows.h>
using namespace std;
int main() {
char i;
while (true) {
for (i = 8; i <= 255; i++) {
if (GetAsyncKeyState(i) == -32767) {
string sound = i + ".wav";
PlaySound(TEXT(sound), NULL, SND_FILENAME | SND_ASYNC);
}
}
}
return 0;
}
Upvotes: 0
Views: 745
Reputation: 420
The solution depends on what your "Character Set" property (Project Properties / Advanced / Character Set) is set to.
In case of "Use Multi-Byte Character Set":
string sound = to_string(i) + ".wav";
PlaySound(sound.c_str(), NULL, SND_FILENAME | SND_ASYNC);
In case of "Use Unicode Character Set":
wstring sound = to_wstring(i) + L".wav";
PlaySound(sound.c_str(), NULL, SND_FILENAME | SND_ASYNC);
Also, don't forget to include the string
header file with #include <string>
.
Upvotes: 0
Reputation: 11158
Just pass a wide string from the start.
std::wstring sound = i + L".wav";
PlaySound(sound.c_str(), NULL, ...
In Windows, native strings are UTF-16 and are represented by wchar_t and variants of w in STL (wstring etc).
Upvotes: 0
Reputation: 197
You must convert the string to LPCTSTR
Using How to convert std::string to LPCWSTR in C++ (Unicode)
#include <iostream>
#include <Windows.h>
using namespace std;
std::wstring s2ws(const std::string& s)
{
int len;
int slength = (int)s.length() + 1;
len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
std::wstring r(buf);
delete[] buf;
return r;
}
int main() {
while (true) {
for (int i = 8; i <= 255; i++) {
if (GetAsyncKeyState(i) == -32767) {
string sound = i + ".wav";
PlaySound(s2ws(sound).c_str(), NULL, SND_FILENAME | SND_ASYNC);
}
}
}
return 0;
}
Upvotes: 0