tts_macos.mm 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. /**************************************************************************/
  2. /* tts_macos.mm */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "tts_macos.h"
  31. @implementation TTS_MacOS
  32. - (id)init {
  33. self = [super init];
  34. self->speaking = false;
  35. self->have_utterance = false;
  36. self->last_utterance = -1;
  37. self->paused = false;
  38. if (@available(macOS 10.14, *)) {
  39. self->synth = [[AVSpeechSynthesizer alloc] init];
  40. [self->synth setDelegate:self];
  41. print_verbose("Text-to-Speech: AVSpeechSynthesizer initialized.");
  42. } else {
  43. self->synth = [[NSSpeechSynthesizer alloc] init];
  44. [self->synth setDelegate:self];
  45. print_verbose("Text-to-Speech: NSSpeechSynthesizer initialized.");
  46. }
  47. return self;
  48. }
  49. // AVSpeechSynthesizer callback (macOS 10.14+)
  50. - (void)speechSynthesizer:(AVSpeechSynthesizer *)av_synth willSpeakRangeOfSpeechString:(NSRange)characterRange utterance:(AVSpeechUtterance *)utterance API_AVAILABLE(macosx(10.14)) {
  51. NSString *string = [utterance speechString];
  52. // Convert from UTF-16 to UTF-32 position.
  53. int pos = 0;
  54. for (NSUInteger i = 0; i < MIN(characterRange.location, string.length); i++) {
  55. unichar c = [string characterAtIndex:i];
  56. if ((c & 0xfffffc00) == 0xd800) {
  57. i++;
  58. }
  59. pos++;
  60. }
  61. DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_BOUNDARY, ids[utterance], pos);
  62. }
  63. // AVSpeechSynthesizer callback (macOS 10.14+)
  64. - (void)speechSynthesizer:(AVSpeechSynthesizer *)av_synth didCancelSpeechUtterance:(AVSpeechUtterance *)utterance API_AVAILABLE(macosx(10.14)) {
  65. DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, ids[utterance]);
  66. ids.erase(utterance);
  67. speaking = false;
  68. [self update];
  69. }
  70. // AVSpeechSynthesizer callback (macOS 10.14+)
  71. - (void)speechSynthesizer:(AVSpeechSynthesizer *)av_synth didFinishSpeechUtterance:(AVSpeechUtterance *)utterance API_AVAILABLE(macosx(10.14)) {
  72. DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_ENDED, ids[utterance]);
  73. ids.erase(utterance);
  74. speaking = false;
  75. [self update];
  76. }
  77. // NSSpeechSynthesizer callback (macOS 10.4+)
  78. - (void)speechSynthesizer:(NSSpeechSynthesizer *)ns_synth willSpeakWord:(NSRange)characterRange ofString:(NSString *)string {
  79. if (!paused && have_utterance) {
  80. // Convert from UTF-16 to UTF-32 position.
  81. int pos = 0;
  82. for (NSUInteger i = 0; i < MIN(characterRange.location, string.length); i++) {
  83. unichar c = [string characterAtIndex:i];
  84. if ((c & 0xfffffc00) == 0xd800) {
  85. i++;
  86. }
  87. pos++;
  88. }
  89. DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_BOUNDARY, last_utterance, pos);
  90. }
  91. }
  92. - (void)speechSynthesizer:(NSSpeechSynthesizer *)ns_synth didFinishSpeaking:(BOOL)success {
  93. if (!paused && have_utterance) {
  94. if (success) {
  95. DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_ENDED, last_utterance);
  96. } else {
  97. DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, last_utterance);
  98. }
  99. have_utterance = false;
  100. }
  101. speaking = false;
  102. [self update];
  103. }
  104. - (void)update {
  105. if (!speaking && queue.size() > 0) {
  106. DisplayServer::TTSUtterance &message = queue.front()->get();
  107. if (@available(macOS 10.14, *)) {
  108. AVSpeechSynthesizer *av_synth = synth;
  109. AVSpeechUtterance *new_utterance = [[AVSpeechUtterance alloc] initWithString:[NSString stringWithUTF8String:message.text.utf8().get_data()]];
  110. [new_utterance setVoice:[AVSpeechSynthesisVoice voiceWithIdentifier:[NSString stringWithUTF8String:message.voice.utf8().get_data()]]];
  111. if (message.rate > 1.f) {
  112. [new_utterance setRate:Math::remap(message.rate, 1.f, 10.f, AVSpeechUtteranceDefaultSpeechRate, AVSpeechUtteranceMaximumSpeechRate)];
  113. } else if (message.rate < 1.f) {
  114. [new_utterance setRate:Math::remap(message.rate, 0.1f, 1.f, AVSpeechUtteranceMinimumSpeechRate, AVSpeechUtteranceDefaultSpeechRate)];
  115. }
  116. [new_utterance setPitchMultiplier:message.pitch];
  117. [new_utterance setVolume:(Math::remap(message.volume, 0.f, 100.f, 0.f, 1.f))];
  118. ids[new_utterance] = message.id;
  119. [av_synth speakUtterance:new_utterance];
  120. } else {
  121. NSSpeechSynthesizer *ns_synth = synth;
  122. [ns_synth setObject:nil forProperty:NSSpeechResetProperty error:nil];
  123. [ns_synth setVoice:[NSString stringWithUTF8String:message.voice.utf8().get_data()]];
  124. int base_pitch = [[ns_synth objectForProperty:NSSpeechPitchBaseProperty error:nil] intValue];
  125. [ns_synth setObject:[NSNumber numberWithInt:(base_pitch * (message.pitch / 2.f + 0.5f))] forProperty:NSSpeechPitchBaseProperty error:nullptr];
  126. [ns_synth setVolume:(Math::remap(message.volume, 0.f, 100.f, 0.f, 1.f))];
  127. [ns_synth setRate:(message.rate * 200)];
  128. last_utterance = message.id;
  129. have_utterance = true;
  130. [ns_synth startSpeakingString:[NSString stringWithUTF8String:message.text.utf8().get_data()]];
  131. }
  132. queue.pop_front();
  133. DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_STARTED, message.id);
  134. speaking = true;
  135. }
  136. }
  137. - (void)pauseSpeaking {
  138. if (@available(macOS 10.14, *)) {
  139. AVSpeechSynthesizer *av_synth = synth;
  140. [av_synth pauseSpeakingAtBoundary:AVSpeechBoundaryImmediate];
  141. } else {
  142. NSSpeechSynthesizer *ns_synth = synth;
  143. [ns_synth pauseSpeakingAtBoundary:NSSpeechImmediateBoundary];
  144. }
  145. paused = true;
  146. }
  147. - (void)resumeSpeaking {
  148. if (@available(macOS 10.14, *)) {
  149. AVSpeechSynthesizer *av_synth = synth;
  150. [av_synth continueSpeaking];
  151. } else {
  152. NSSpeechSynthesizer *ns_synth = synth;
  153. [ns_synth continueSpeaking];
  154. }
  155. paused = false;
  156. }
  157. - (void)stopSpeaking {
  158. for (DisplayServer::TTSUtterance &message : queue) {
  159. DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, message.id);
  160. }
  161. queue.clear();
  162. if (@available(macOS 10.14, *)) {
  163. AVSpeechSynthesizer *av_synth = synth;
  164. [av_synth stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
  165. } else {
  166. NSSpeechSynthesizer *ns_synth = synth;
  167. if (have_utterance) {
  168. DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, last_utterance);
  169. }
  170. [ns_synth stopSpeaking];
  171. }
  172. have_utterance = false;
  173. speaking = false;
  174. paused = false;
  175. }
  176. - (bool)isSpeaking {
  177. return speaking || (queue.size() > 0);
  178. }
  179. - (bool)isPaused {
  180. if (@available(macOS 10.14, *)) {
  181. AVSpeechSynthesizer *av_synth = synth;
  182. return [av_synth isPaused];
  183. } else {
  184. return paused;
  185. }
  186. }
  187. - (void)speak:(const String &)text voice:(const String &)voice volume:(int)volume pitch:(float)pitch rate:(float)rate utterance_id:(int)utterance_id interrupt:(bool)interrupt {
  188. if (interrupt) {
  189. [self stopSpeaking];
  190. }
  191. if (text.is_empty()) {
  192. DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, utterance_id);
  193. return;
  194. }
  195. DisplayServer::TTSUtterance message;
  196. message.text = text;
  197. message.voice = voice;
  198. message.volume = CLAMP(volume, 0, 100);
  199. message.pitch = CLAMP(pitch, 0.f, 2.f);
  200. message.rate = CLAMP(rate, 0.1f, 10.f);
  201. message.id = utterance_id;
  202. queue.push_back(message);
  203. if ([self isPaused]) {
  204. [self resumeSpeaking];
  205. } else {
  206. [self update];
  207. }
  208. }
  209. - (Array)getVoices {
  210. Array list;
  211. if (@available(macOS 10.14, *)) {
  212. for (AVSpeechSynthesisVoice *voice in [AVSpeechSynthesisVoice speechVoices]) {
  213. NSString *voiceIdentifierString = [voice identifier];
  214. NSString *voiceLocaleIdentifier = [voice language];
  215. NSString *voiceName = [voice name];
  216. Dictionary voice_d;
  217. voice_d["name"] = String::utf8([voiceName UTF8String]);
  218. voice_d["id"] = String::utf8([voiceIdentifierString UTF8String]);
  219. voice_d["language"] = String::utf8([voiceLocaleIdentifier UTF8String]);
  220. list.push_back(voice_d);
  221. }
  222. } else {
  223. for (NSString *voiceIdentifierString in [NSSpeechSynthesizer availableVoices]) {
  224. NSString *voiceLocaleIdentifier = [[NSSpeechSynthesizer attributesForVoice:voiceIdentifierString] objectForKey:NSVoiceLocaleIdentifier];
  225. NSString *voiceName = [[NSSpeechSynthesizer attributesForVoice:voiceIdentifierString] objectForKey:NSVoiceName];
  226. Dictionary voice_d;
  227. voice_d["name"] = String([voiceName UTF8String]);
  228. voice_d["id"] = String([voiceIdentifierString UTF8String]);
  229. voice_d["language"] = String([voiceLocaleIdentifier UTF8String]);
  230. list.push_back(voice_d);
  231. }
  232. }
  233. return list;
  234. }
  235. @end