#include<bits/stdc++.h>
using namespace std;
class SimpleTTS {
public:
static bool speak(const std::string& text) {
if (text.empty()) return true;
// 检查平台并选择合适的朗读方式
#ifdef _WIN32
return speakWindows(text);
#else
return speakLinux(text);
#endif
}
static bool speakAsync(const std::string& text) {
#ifdef _WIN32
return speakWindowsAsync(text);
#else
return speakLinuxAsync(text);
#endif
}
private:
// Windows 实现 - 使用 PowerShell 避免链接问题
static bool speakWindows(const std::string& text) {
std::string command = "powershell -Command \""
"Add-Type -AssemblyName System.Speech; "
"$speak = New-Object System.Speech.Synthesis.SpeechSynthesizer; "
"$speak.Speak('" + escapeText(text) + "')\"";
int result = system(command.c_str());
return result == 0;
}
static bool speakWindowsAsync(const std::string& text) {
std::string command = "powershell -Command \""
"Add-Type -AssemblyName System.Speech; "
"$speak = New-Object System.Speech.Synthesis.SpeechSynthesizer; "
"$speak.Speak('" + escapeText(text) + "')\" &";
int result = system(command.c_str());
return result == 0;
}
// Linux 实现 - 使用 eSpeak
static bool speakLinux(const std::string& text) {
std::string command = "espeak \"" + escapeText(text) + "\"";
int result = system(command.c_str());
return result == 0;
}
static bool speakLinuxAsync(const std::string& text) {
std::string command = "espeak \"" + escapeText(text) + "\" &";
int result = system(command.c_str());
return result == 0;
}
static std::string escapeText(const std::string& text) {
std::string result = text;
size_t pos = 0;
// 转义单引号(Windows PowerShell)
while ((pos = result.find("'", pos)) != std::string::npos) {
result.replace(pos, 1, "''");
pos += 2;
}
// 转义双引号(Linux espeak)
pos = 0;
while ((pos = result.find("\"", pos)) != std::string::npos) {
result.replace(pos, 1, "\\\"");
pos += 2;
}
return result;
}
};
// 使用示例
int main() {
std::cout << "开始文本朗读测试..." << std::endl;
// 同步朗读
SimpleTTS::speak("你好,这是一个文本朗读测试!");
// 异步朗读
SimpleTTS::speakAsync("这是异步朗读,程序不会阻塞。");
std::cout << "程序继续执行..." << std::endl;
// 等待一段时间让异步朗读完成
std::this_thread::sleep_for(std::chrono::seconds(5));
return 0;
}luogu__butianyu
1641744
『 我这个人走得很慢,但是我从不后退 』
资料、奖项与版本
资料
- 编号
- 1641744
- 抓取
陶片放逐
- − 发送私信
个人介绍
文章
还没有收录这位用户的文章。