C++ PlaySound() 给出错误

C++ PlaySound() giving errors

我正在尝试使用 PlaySound(); C++中的函数。我想让用户输入他们想播放的文件。但是当我把变量放在 PlaySound();它给了我一个错误。这是代码,

#include <string>
#include <Windows.h>
using namespace std;
int main()
{
    cout << "Enter song name...\nMake sure the song is in the same folder as this program\n";
    string filename;
    getline(cin, filename);
    cout << "Playing song...\n";
    bool played = PlaySound(TEXT(filename), NULL, SND_SYNC);


    return 0;
}

错误, identifier "Lfilename" is undefined 'Lfilename': undeclared identifier 我正在使用 Microsoft Visual Studio 2019.

您不能改用 TEXT() macro with a variable, only with a compile-time character/string literal. You need to use the std::string::c_str() 方法。

此外,TEXT()L 前缀添加到指定标识符的事实意味着您正在为 Unicode 编译项目(即 UNICODE 在预处理期间定义),这意味着 PlaySound()(作为一个基于 TCHAR 的宏本身)将映射到 PlaySoundW(),它期望一个宽强的输入而不是一个窄字符串。所以你需要调用 PlaySoundA() 来匹配你对 std::string.

的使用

试试这个:

#include <string>
#include <Windows.h>
using namespace std;

int main() {
    cout << "Enter song name...\nMake sure the song is in the same folder as this program\n";
    string filename;
    getline(cin, filename);
    cout << "Playing song...\n";
    bool played = PlaySoundA(filename.c_str(), NULL, SND_SYNC);

    return 0;
}

或者,使用 std::wstring,因为 Windows API 更喜欢 Unicode 字符串(基于 ANSI 的 API 在内部调用 Unicode API):

#include <string>
#include <Windows.h>
using namespace std;

int main() {
    wcout << L"Enter song name...\nMake sure the song is in the same folder as this program\n";
    wstring filename;
    getline(wcin, filename);
    wcout << L"Playing song...\n";
    bool played = PlaySoundW(filename.c_str(), NULL, SND_SYNC);

    return 0;
}