tts_osx.mm 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. /**************************************************************************/
  2. /* tts_osx.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_osx.h"
  31. @implementation TTS_OSX
  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. OS::get_singleton()->tts_post_utterance_event(OS::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. OS::get_singleton()->tts_post_utterance_event(OS::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. OS::get_singleton()->tts_post_utterance_event(OS::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. OS::get_singleton()->tts_post_utterance_event(OS::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. OS::get_singleton()->tts_post_utterance_event(OS::TTS_UTTERANCE_ENDED, last_utterance);
  96. } else {
  97. OS::get_singleton()->tts_post_utterance_event(OS::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. OS::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::range_lerp(message.rate, 1.f, 10.f, AVSpeechUtteranceDefaultSpeechRate, AVSpeechUtteranceMaximumSpeechRate)];
  113. } else if (message.rate < 1.f) {
  114. [new_utterance setRate:Math::range_lerp(message.rate, 0.1f, 1.f, AVSpeechUtteranceMinimumSpeechRate, AVSpeechUtteranceDefaultSpeechRate)];
  115. }
  116. [new_utterance setPitchMultiplier:message.pitch];
  117. [new_utterance setVolume:(Math::range_lerp(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::range_lerp(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. OS::get_singleton()->tts_post_utterance_event(OS::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 (List<OS::TTSUtterance>::Element *E = queue.front(); E; E = E->next()) {
  159. OS::TTSUtterance &message = E->get();
  160. OS::get_singleton()->tts_post_utterance_event(OS::TTS_UTTERANCE_CANCELED, message.id);
  161. }
  162. queue.clear();
  163. if (@available(macOS 10.14, *)) {
  164. AVSpeechSynthesizer *av_synth = synth;
  165. [av_synth stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
  166. } else {
  167. NSSpeechSynthesizer *ns_synth = synth;
  168. if (have_utterance) {
  169. OS::get_singleton()->tts_post_utterance_event(OS::TTS_UTTERANCE_CANCELED, last_utterance);
  170. }
  171. [ns_synth stopSpeaking];
  172. }
  173. have_utterance = false;
  174. speaking = false;
  175. paused = false;
  176. }
  177. - (bool)isSpeaking {
  178. return speaking || (queue.size() > 0);
  179. }
  180. - (bool)isPaused {
  181. if (@available(macOS 10.14, *)) {
  182. AVSpeechSynthesizer *av_synth = synth;
  183. return [av_synth isPaused];
  184. } else {
  185. return paused;
  186. }
  187. }
  188. - (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 {
  189. if (interrupt) {
  190. [self stopSpeaking];
  191. }
  192. if (text.empty()) {
  193. OS::get_singleton()->tts_post_utterance_event(OS::TTS_UTTERANCE_CANCELED, utterance_id);
  194. return;
  195. }
  196. OS::TTSUtterance message;
  197. message.text = text;
  198. message.voice = voice;
  199. message.volume = CLAMP(volume, 0, 100);
  200. message.pitch = CLAMP(pitch, 0.f, 2.f);
  201. message.rate = CLAMP(rate, 0.1f, 10.f);
  202. message.id = utterance_id;
  203. queue.push_back(message);
  204. if ([self isPaused]) {
  205. [self resumeSpeaking];
  206. } else {
  207. [self update];
  208. }
  209. }
  210. - (Array)getVoices {
  211. Array list;
  212. if (@available(macOS 10.14, *)) {
  213. for (AVSpeechSynthesisVoice *voice in [AVSpeechSynthesisVoice speechVoices]) {
  214. NSString *voiceIdentifierString = [voice identifier];
  215. NSString *voiceLocaleIdentifier = [voice language];
  216. NSString *voiceName = [voice name];
  217. Dictionary voice_d;
  218. voice_d["name"] = String::utf8([voiceName UTF8String]);
  219. voice_d["id"] = String::utf8([voiceIdentifierString UTF8String]);
  220. voice_d["language"] = String::utf8([voiceLocaleIdentifier UTF8String]);
  221. list.push_back(voice_d);
  222. }
  223. } else {
  224. for (NSString *voiceIdentifierString in [NSSpeechSynthesizer availableVoices]) {
  225. NSString *voiceLocaleIdentifier = [[NSSpeechSynthesizer attributesForVoice:voiceIdentifierString] objectForKey:NSVoiceLocaleIdentifier];
  226. NSString *voiceName = [[NSSpeechSynthesizer attributesForVoice:voiceIdentifierString] objectForKey:NSVoiceName];
  227. Dictionary voice_d;
  228. voice_d["name"] = String([voiceName UTF8String]);
  229. voice_d["id"] = String([voiceIdentifierString UTF8String]);
  230. voice_d["language"] = String([voiceLocaleIdentifier UTF8String]);
  231. list.push_back(voice_d);
  232. }
  233. }
  234. return list;
  235. }
  236. @end