C++ PlaySound() 给出错误

标签 c++ playsound

我正在尝试使用 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;
}

错误, 标识符“Lfilename”未定义 'Lfilename': 未声明的标识符 我正在使用 Microsoft Visual Studio 2019。

最佳答案

您不能使用 TEXT()带有变量的宏,仅带有编译时字符/字符串文字。您需要使用 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;
}

关于C++ PlaySound() 给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59340003/

相关文章:

c++ - 如何使用 Windows API 在 C++ 中播放声音?

c++ - 使用 Clang 编译时的最大错误数

c++ - 程序有问题吗

c++ - 子进程更新共享的mmap内存,但父进程未更改

python - 安装 PyOpenCL 时出现问题

python - 如何在python中连续和异步播放不同的声音?

c++ - 使用 enable_if 匹配数字作为函数参数

Azure 虚拟机麦克风和扬声器

javascript - 在 safari 中使用 javascript 播放声音

java - Java应用程序将无法播放声音