我目前正在使用命名空间Windows::Media::SpeechSynthesis
开发UWP DLL应用程序。我创建了一个函数,允许我说出输入的文本,如下所示:
int TextToSpeechUwpDll::ttsSpeak( const char* text )
{
SpeechSynthesizer ^speak = ref new SpeechSynthesizer();
MediaPlayer ^player = ref new MediaPlayer;
int wchars_num = MultiByteToWideChar( CP_ACP, 0, text, -1, NULL, 0 );
wchar_t* texts = new wchar_t[wchars_num];
MultiByteToWideChar( CP_ACP, 0, text, -1, texts, wchars_num );
String ^sentence = ref new String( texts );
task<SpeechSynthesisStream ^> speakTask = create_task( speak->SynthesizeTextToStreamAsync( sentence ) );
speakTask.then( [player, sentence]( SpeechSynthesisStream ^speechStream )
{
player->Source = MediaSource::CreateFromStream( speechStream, speechStream->ContentType );
player->AutoPlay = true;
player->Play();
Sleep( 3000 );
} );
return true;
}
但是,需要删除Sleep( 3000 );
,因为当我输入一个句子时,它只会说出 3 秒钟,这意味着如果它比这更长,其余的都不会被说出来。我试图删除这一行,但是当我这样做时,根本没有说什么。没有声音出来。延长持续时间并不能解决我的问题。我正在寻找的是没有时间限制地说一句话的能力。以前有人遇到过这个问题吗?
你应该声明一个关于你的 MediaPlayer ^player 的私有属性,以便在局部变量 "player" 被释放时保存它。
在 .h 中
class TextToSpeechUwpDll
{
//......
private:
MediaPlayer ^player = ref new MediaPlayer();
};
在.cpp
SpeechSynthesizer ^speak = ref new SpeechSynthesizer();
char* text = "helloworld";
int wchars_num = MultiByteToWideChar(CP_ACP, 0, text, -1, NULL, 0);
wchar_t* texts = new wchar_t[wchars_num];
MultiByteToWideChar(CP_ACP, 0, text, -1, texts, wchars_num);
String ^sentence = ref new String(texts);
task<SpeechSynthesisStream ^> speakTask = create_task(speak->SynthesizeTextToStreamAsync(sentence));
speakTask.then([this, sentence](SpeechSynthesisStream ^speechStream)
{
player->Source = MediaSource::CreateFromStream(speechStream, speechStream->ContentType);
player->AutoPlay = true;
player->Play();
});