如何将字符串数组元素传入PlaySound()函数实现wav音频播放?
实现方法
你需要先将遍历到的单词和.wav后缀拼接为完整的文件名,再传入PlaySound函数即可,同时要注意字符集适配和循环变量的顺序问题,以下是可直接运行的修改方案:
1. 调整循环变量位置
你原有代码的i++放在了PlaySound调用前,后续要读取str[i]的话会出现下标错位、最后一次越界的问题,需要将i++移到循环体末尾。
2. 按项目字符集选择实现
情况A:多字节字符集(str为std::string/C风格char数组)
int i = 0; while (i < count) { cout << "now playing:" << str[i] << endl; // 拼接完整音频文件名 std::string audio_file = str[i] + ".wav"; bool played = PlaySound(audio_file.c_str(), NULL, SND_SYNC); cout << "played ?" << played << endl; i++; }
如果str是C风格char数组,拼接逻辑替换为:
char audio_file[128]; sprintf(audio_file, "%s.wav", str[i]); bool played = PlaySound(audio_file, NULL, SND_SYNC);
情况B:Unicode字符集(Visual Studio默认项目配置,str为std::wstring数组)
int i = 0; while (i < count) { wcout << L"now playing:" << str[i] << endl; std::wstring audio_file = str[i] + L".wav"; bool played = PlaySound(audio_file.c_str(), NULL, SND_SYNC); cout << "played ?" << played << endl; i++; }
补充说明
- 不要尝试用
TEXT()宏包裹字符串变量,该宏仅适用于编译期确定的字符串常量,对运行时生成的字符串无效 - 需要保证
Can.wav、You.wav等音频文件存放在程序运行的工作目录下,否则需要拼接完整绝对路径传入
内容的提问来源于stack exchange,提问作者Belengaz
相关产品推荐
相关产品推荐

