-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlisting6.html
executable file
·1520 lines (1221 loc) · 61.1 KB
/
listing6.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
<html>
<head>
<!-- BEGIN META TAG INFO -->
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="home" href="http://developer.apple.com/">
<link rel="find" href="http://developer.apple.com/search/">
<link rel="stylesheet" type="text/css" href="../../documentation/css/adcstyle.css" title="fonts">
<script language="JavaScript" src="../../documentation/js/adc.js" type="text/javascript"></script>
<!-- END META TAG INFO -->
<!-- BEGIN TITLE -->
<title>CocoaSpeechSynthesisExample - /SpeakingTextWindow.m</title>
<!-- END TITLE -->
<script language="JavaScript">
function JumpToNewPage() {
window.location=document.scpopupmenu.gotop.value;
return true;
}
</script>
</head>
<!-- BEGIN BODY OPEN -->
<body>
<!--END BODY OPEN -->
<!-- START CENTER OPEN -->
<center>
<!-- END CENTER OPEN -->
<!-- BEGIN LOGO AND SEARCH -->
<!--#include virtual="/includes/adcnavbar"-->
<!-- END LOGO AND SEARCH -->
<!-- START BREADCRUMB -->
<div id="breadcrumb">
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr>
<td scope="row"><img width="340" height="10" src="images/1dot.gif" alt=""></td>
<td><img width="340" height="10" src="images/1dot.gif" alt=""></td>
</tr>
<tr valign="middle">
<td align="left" colspan="2">
<a href="http://developer.apple.com/">ADC Home</a> > <a href="../../referencelibrary/index.html">Reference Library</a> > <a href="../../samplecode/index.html">Sample Code</a> > <a href="../../samplecode/UserExperience/index.html">User Experience</a> > <a href="../../samplecode/UserExperience/idxSpeechTechnologies-date.html">Speech Technologies</a> > <A HREF="javascript:location.replace('index.html');">CocoaSpeechSynthesisExample</A> >
</td>
</tr>
<tr>
<td colspan="2" scope="row"><img width="680" height="35" src="images/1dot.gif" alt=""></td>
</tr>
</table>
</div>
<!-- END BREADCRUMB -->
<!-- START MAIN CONTENT -->
<!-- START TITLE GRAPHIC AND INTRO-->
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr align="left" valign="top">
<td><h1><div id="pagehead">CocoaSpeechSynthesisExample</div></h1></td>
</tr>
</table>
<!-- END TITLE GRAPHIC AND INTRO -->
<!-- START WIDE COLUMN -->
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr align="left" valign="top">
<td id="scdetails">
<h2>/SpeakingTextWindow.m</h2>
<form name="scpopupmenu" onSubmit="return false;" method=post>
<p><strong>View Source Code:</strong>
<select name="gotop" onChange="JumpToNewPage();" style="width:340px"><option selected value="ingnore">Select File</option>
<option value="listing1.html">/CocoaSpeechSynthesisExample_main.m</option>
<option value="listing2.html">/ReadMe-CocoaSpeechExample.txt</option>
<option value="listing3.html">/SpeakingCharacterView.h</option>
<option value="listing4.html">/SpeakingCharacterView.m</option>
<option value="listing5.html">/SpeakingTextWindow.h</option>
<option value="listing6.html">/SpeakingTextWindow.m</option></select>
</p>
</form>
<p><strong><a href="CocoaSpeechSynthesisExample.zip">Download Sample</a></strong> (“CocoaSpeechSynthesisExample.zip”, 196.0K)<BR>
<strong><a href="CocoaSpeechSynthesisExample.dmg">Download Sample</a></strong> (“CocoaSpeechSynthesisExample.dmg”, 223.6K)</p>
<!--
<p><strong><a href="#">Download Sample</a></strong> (“filename.sit”, 500K)</p>
-->
</td>
</tr>
<tr>
<td scope="row"><img width="680" height="10" src="images/1dot.gif" alt=""><br>
<img height="1" width="680" src="images/1dot_919699.gif" alt=""><br>
<img width="680" height="20" src="images/1dot.gif" alt=""></td>
</tr>
<tr>
<td scope="row">
<!--googleon: index -->
<pre class="sourcecodebox">/*
File: SpeakingTextWindow.m
Abstract: The main window hosting all the apps speech features.
Version: 1.4
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple
Inc. ("Apple") in consideration of your agreement to the
following terms, and your use, installation, modification or
redistribution of this Apple software constitutes acceptance of these
terms. If you do not agree with these terms, please do not use,
install, modify or redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and
subject to these terms, Apple grants you a personal, non-exclusive
license, under Apple's copyrights in this original Apple software (the
"Apple Software"), to use, reproduce, modify and redistribute the Apple
Software, with or without modifications, in source and/or binary forms;
provided that if you redistribute the Apple Software in its entirety and
without modifications, you must retain this notice and the following
text and disclaimers in all such redistributions of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc.
may be used to endorse or promote products derived from the Apple
Software without specific prior written permission from Apple. Except
as expressly stated in this notice, no other rights or licenses, express
or implied, are granted by Apple herein, including but not limited to
any patent rights that may be infringed by your derivative works or by
other works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
Copyright © 2000-2007 Apple Inc. All Rights Reserved
*/
#import "SpeakingTextWindow.h"
//
// Constants
//
NSString * kPlainTextDataTypeString = @"Plain Text";
NSString * kDefaultWindowTextString = @"Welcome to Cocoa Speech Synthesis Example. This application provides an example of using Apple's speech synthesis technology in a Cocoa-based application.";
NSString * kWordCallbackParamPosition = @"ParamPosition";
NSString * kWordCallbackParamLength = @"ParamLength";
NSString * kErrorCallbackParamPosition = @"ParamPosition";
NSString * kErrorCallbackParamError = @"ParamError";
//
// Prototypes
//
static pascal void OurErrorCallBackProc(SpeechChannel inSpeechChannel, long inRefCon, OSErr inError, long inBytePos);
static pascal void OurTextDoneCallBackProc(SpeechChannel inSpeechChannel, long inRefCon, const void ** nextBuf, unsigned long * byteLen, long * controlFlags);
static pascal void OurSpeechDoneCallBackProc(SpeechChannel inSpeechChannel, long inRefCon);
static pascal void OurSyncCallBackProc(SpeechChannel inSpeechChannel, long inRefCon, OSType inSyncMessage);
static pascal void OurPhonemeCallBackProc(SpeechChannel inSpeechChannel, long inRefCon, short inPhonemeOpcode);
static pascal void OurWordCallBackProc(SpeechChannel inSpeechChannel, long inRefCon, long inWordPos, short inWordLen);
static UInt32 BCDNumToLong(UInt32 inBCDNum);
static NSString* VersionNumToString(NumVersion inVersionNum);
//
// SpeechLibTestShellWindow object
//
@implementation SpeakingTextWindow
/*----------------------------------------------------------------------------------------
init
Set the default text of the window.
----------------------------------------------------------------------------------------*/
- (id)init
{
if (self = [super init]) {
// Set our default window text.
[self setTextData:[NSData dataWithBytes:[kDefaultWindowTextString cString] length:[kDefaultWindowTextString cStringLength]]];
[self setTextDataType:kPlainTextDataTypeString];
}
return self;
}
/*----------------------------------------------------------------------------------------
dealloc
Release any memory we allocated while the window was showing.
----------------------------------------------------------------------------------------*/
-(void)dealloc
{
[fTextData release];
[fTextDataType release];
[super dealloc];
}
/*----------------------------------------------------------------------------------------
setTextData:
Set our text data variable and update text in window if showing.
----------------------------------------------------------------------------------------*/
- (void)setTextData:(NSData *)theData
{
[theData retain];
[fTextData release];
fTextData = theData;
// If the window is showing, update the text view.
if (fSpokenTextView) {
if ([[self textDataType] isEqualToString:@"RTF Document"])
[fSpokenTextView replaceCharactersInRange:NSMakeRange(0,[[fSpokenTextView string] length]) withRTF:[self textData]];
else
[fSpokenTextView replaceCharactersInRange:NSMakeRange(0,[[fSpokenTextView string] length]) withString:[NSString stringWithCString:[[self textData] bytes] length:[[self textData] length]]];
}
}
/*----------------------------------------------------------------------------------------
textData
Returns autoreleased copy of text data.
----------------------------------------------------------------------------------------*/
- (NSData *)textData
{
return [[fTextData copy] autorelease];
}
/*----------------------------------------------------------------------------------------
setTextDataType:
Set our text data type variable.
----------------------------------------------------------------------------------------*/
- (void)setTextDataType:(NSString *)theType
{
[theType retain];
[fTextDataType release];
fTextDataType = theType;
}
/*----------------------------------------------------------------------------------------
textDataType
Returns autoreleased copy of text data.
----------------------------------------------------------------------------------------*/
- (NSString *)textDataType
{
return [[fTextDataType copy] autorelease];
}
/*----------------------------------------------------------------------------------------
textDataType
Returns reference to character view for callbacks.
----------------------------------------------------------------------------------------*/
- (SpeakingCharacterView *)characterView
{
return fCharacterView;
}
/*----------------------------------------------------------------------------------------
shouldDisplayWordCallbacks
Returns true if user has chosen to have words hightlight during synthesis.
----------------------------------------------------------------------------------------*/
- (BOOL)shouldDisplayWordCallbacks
{
return [fHandleWordCallbacksCheckboxButton intValue];
}
/*----------------------------------------------------------------------------------------
shouldDisplayPhonemeCallbacks
Returns true if user has chosen to the character animate phonemes during synthesis.
----------------------------------------------------------------------------------------*/
- (BOOL)shouldDisplayPhonemeCallbacks
{
return [fHandlePhonemeCallbacksCheckboxButton intValue];
}
/*----------------------------------------------------------------------------------------
shouldDisplayErrorCallbacks
Returns true if user has chosen to have an alert appear in response to an error callback.
----------------------------------------------------------------------------------------*/
- (BOOL)shouldDisplayErrorCallbacks
{
return [fHandleErrorCallbacksCheckboxButton intValue];
}
/*----------------------------------------------------------------------------------------
shouldDisplaySyncCallbacks
Returns true if user has chosen to have an alert appear in response to an sync callback.
----------------------------------------------------------------------------------------*/
- (BOOL)shouldDisplaySyncCallbacks
{
return [fHandleSyncCallbacksCheckboxButton intValue];
}
/*----------------------------------------------------------------------------------------
shouldDisplaySpeechDoneCallbacks
Returns true if user has chosen to have an alert appear when synthesis is finished.
----------------------------------------------------------------------------------------*/
- (BOOL)shouldDisplaySpeechDoneCallbacks
{
return [fHandleSpeechDoneCallbacksCheckboxButton intValue];
}
/*----------------------------------------------------------------------------------------
shouldDisplayTextDoneCallbacks
Returns true if user has chosen to have an alert appear when text processing is finished.
----------------------------------------------------------------------------------------*/
- (BOOL)shouldDisplayTextDoneCallbacks
{
return [fHandleTextDoneCallbacksCheckboxButton intValue];
}
/*----------------------------------------------------------------------------------------
awakeFromNib
This routine is call once right after our nib file is loaded. We build our voices
pop-up menu, create a new speech channel and update our window using parameters from
the new speech channel.
----------------------------------------------------------------------------------------*/
- (void)awakeFromNib
{
OSErr theErr = noErr;
//
// Build the Voices pop-up menu
//
{
short numOfVoices;
long voiceIndex;
BOOL voiceFoundAndSelected = false;
VoiceSpec theVoiceSpec;
// Delete the existing voices from the bottom of the menu.
while([fVoicesPopUpButton numberOfItems] > 2)
[fVoicesPopUpButton removeItemAtIndex:2];
// Ask TTS API for each available voicez
theErr = CountVoices(&numOfVoices);
if (theErr != noErr)
NSRunAlertPanel(@"CountVoices", [NSString stringWithFormat:@"Error #%d returned.", theErr], @"Oh?", NULL, NULL);
if (theErr == noErr) {
for (voiceIndex = 1; voiceIndex <= numOfVoices; voiceIndex++) {
VoiceDescription theVoiceDesc;
theErr = GetIndVoice(voiceIndex, &theVoiceSpec);
if (theErr != noErr)
NSRunAlertPanel(@"GetIndVoice", [NSString stringWithFormat:@"Error #%d returned.", theErr], @"Oh?", NULL, NULL);
if (theErr == noErr)
theErr = GetVoiceDescription(&theVoiceSpec, &theVoiceDesc, sizeof(theVoiceDesc));
if (theErr != noErr)
NSRunAlertPanel(@"GetVoiceDescription", [NSString stringWithFormat:@"Error #%d returned.", theErr], @"Oh?", NULL, NULL);
if (theErr == noErr) {
// Get voice name and add it to the menu list
NSString *theNameString = [[[NSString alloc]initWithCString:(char *) &(theVoiceDesc.name[1]) length:theVoiceDesc.name[0]]autorelease];
[fVoicesPopUpButton addItemWithTitle:theNameString];
// Selected this item if it matches our default voice spec.
if (theVoiceSpec.creator == fSelectedVoiceCreator && theVoiceSpec.id == fSelectedVoiceID) {
[fVoicesPopUpButton selectItemAtIndex:voiceIndex-1];
voiceFoundAndSelected = true;
}
}
}
// User preference default if problems.
if (! voiceFoundAndSelected && numOfVoices >= 1) {
// Update our object fields with the first voice
fSelectedVoiceCreator = 0;
fSelectedVoiceID = 0;
[fVoicesPopUpButton selectItemAtIndex:0];
}
}
else {
[fVoicesPopUpButton selectItemAtIndex:0];
}
}
// Create Speech Channel configured with our desired options and callbacks
[self createNewSpeechChannel:NULL];
// Set editable default fields
[self fillInEditableParameterFields];
// Enable buttons appropriatelly
[fStartStopButton setEnabled:true];
[fPauseContinueButton setEnabled:false];
[fSaveAsFileButton setEnabled:true];
// Show API version number
[fAPIVersionStaticField setStringValue:VersionNumToString(SpeechManagerVersion())];
// Set starting expresison on animated character
[self phonemeCallbacksButtonPressed:fHandlePhonemeCallbacksCheckboxButton];
}
/*----------------------------------------------------------------------------------------
updateSpeakingControlState
This routine is called when appropriate to update the Start/Stop Speaking,
Pause/Continue Speaking buttons.
----------------------------------------------------------------------------------------*/
- (void)updateSpeakingControlState
{
//
// Update controls based on speaking state
//
[fSaveAsFileButton setEnabled:!fCurrentlySpeaking];
[fPauseContinueButton setEnabled:fCurrentlySpeaking];
[fStartStopButton setEnabled:!fCurrentlyPaused];
if (fCurrentlySpeaking) {
[fStartStopButton setTitle:NSLocalizedString(@"Stop Speaking", @"Stop Speaking")];
[fPauseContinueButton setTitle:NSLocalizedString(@"Pause Speaking", @"Pause Speaking")];
}
else {
[fStartStopButton setTitle:NSLocalizedString(@"Start Speaking", @"Start Speaking")];
[fSpokenTextView setSelectedRange:fOrgSelectionRange]; // Set selection length to zero.
}
if (fCurrentlyPaused)
[fPauseContinueButton setTitle:NSLocalizedString(@"Continue Speaking", @"Continue Speaking")];
else
[fPauseContinueButton setTitle:NSLocalizedString(@"Pause Speaking", @"Pause Speaking")];
[self enableOptionsForSpeakingState:fCurrentlySpeaking];
//
// Update parameter fields.
//
Fixed tempFixedValue = 0;
GetSpeechInfo(fCurSpeechChannel, soRate, &tempFixedValue);
[fRateCurrentStaticField setDoubleValue:(tempFixedValue / 65536.0)];
GetSpeechPitch(fCurSpeechChannel, &tempFixedValue);
[fPitchBaseCurrentStaticField setDoubleValue:(tempFixedValue / 65536.0)];
GetSpeechInfo(fCurSpeechChannel, soPitchMod, &tempFixedValue);
[fPitchModCurrentStaticField setDoubleValue:(tempFixedValue / 65536.0)];
GetSpeechInfo(fCurSpeechChannel, soVolume, &tempFixedValue);
[fVolumeCurrentStaticField setDoubleValue:(tempFixedValue / 65536.0)];
}
/*----------------------------------------------------------------------------------------
highlightWordWithParams:
Highlights the word currently being spoken based on text position and text length
provided in the word callback routine.
----------------------------------------------------------------------------------------*/
- (void)highlightWordWithParams:(NSDictionary *)params
{
UInt32 selectionPosition = [[params objectForKey:kWordCallbackParamPosition] longValue] + fOffsetToSpokenText;
UInt32 wordLength = [[params objectForKey:kWordCallbackParamLength] longValue];
[fSpokenTextView scrollRangeToVisible:NSMakeRange(selectionPosition, wordLength)];
[fSpokenTextView setSelectedRange:NSMakeRange(selectionPosition, wordLength)];
[fSpokenTextView display];
}
/*----------------------------------------------------------------------------------------
displayErrorAlertWithParams:
Displays an alert describing a text processing error provided in the error callback.
----------------------------------------------------------------------------------------*/
- (void)displayErrorAlertWithParams:(NSDictionary *)params
{
UInt32 errorPosition = [[params objectForKey:kErrorCallbackParamPosition] longValue] + fOffsetToSpokenText;
UInt32 errorCode = [[params objectForKey:kErrorCallbackParamError] longValue];
if (errorCode != fLastErrorCode) {
OSErr theErr = noErr;
unsigned long alertButtonClicked;
NSString* theMessageStr = NULL;
// Tell engine to pause while we display this dialog.
theErr = PauseSpeechAt(fCurSpeechChannel, kImmediate);
if (theErr != noErr)
NSRunAlertPanel(@"PauseSpeechAt", [NSString stringWithFormat:@"Error #%d returned.", theErr], @"Oh?", NULL, NULL);
// Select offending character
[fSpokenTextView setSelectedRange:NSMakeRange(errorPosition, 1)];
[fSpokenTextView display];
// Display error alert, and stop or continue based on user's desires
theMessageStr = [NSString stringWithFormat:@"Error #%d occurred at position %d in the text.", errorCode, errorPosition];
alertButtonClicked = NSRunAlertPanel(@"Text Processing Error", theMessageStr, @"Stop", NULL, @"Continue");
if (alertButtonClicked == 1)
[self startStopButtonPressed:fStartStopButton];
else {
theErr = ContinueSpeech(fCurSpeechChannel);
if (theErr != noErr)
NSRunAlertPanel(@"ContinueSpeech", [NSString stringWithFormat:@"Error #%d returned.", theErr], @"Oh?", NULL, NULL);
}
fLastErrorCode = errorCode;
}
}
/*----------------------------------------------------------------------------------------
displaySyncAlertWithMessage:
Displays an alert with information about a sync command in response to a sync callback.
----------------------------------------------------------------------------------------*/
- (void)displaySyncAlertWithMessage:(NSNumber *)messageNumber
{
OSErr theErr = noErr;
unsigned long alertButtonClicked;
NSString* theMessageStr = NULL;
// Tell engine to pause while we display this dialog.
theErr = PauseSpeechAt(fCurSpeechChannel, kImmediate);
if (theErr != noErr)
NSRunAlertPanel(@"PauseSpeechAt", [NSString stringWithFormat:@"Error #%d returned.", theErr], @"Oh?", NULL, NULL);
// Display error alert, and stop or continue based on user's desires
UInt32 theMessageValue = [messageNumber longValue];
theMessageStr = [NSString stringWithFormat:@"Sync embedded command was discovered containing message %d ('%4s').", theMessageValue, &theMessageValue];
alertButtonClicked = NSRunAlertPanel(@"Sync Callback", theMessageStr, @"Stop", NULL, @"Continue");
if (alertButtonClicked == 1)
[self startStopButtonPressed:fStartStopButton];
else
{
theErr = ContinueSpeech(fCurSpeechChannel);
if (theErr != noErr)
NSRunAlertPanel(@"ContinueSpeech", [NSString stringWithFormat:@"Error #%d returned.", theErr], @"Oh?", NULL, NULL);
}
}
/*----------------------------------------------------------------------------------------
speechIsDone
Updates user interface and optionally displays an alert when generation of speech is
finish.
----------------------------------------------------------------------------------------*/
- (void)speechIsDone
{
fCurrentlySpeaking = false;
[self updateSpeakingControlState];
[self enableCallbackControlsBasedOnSavingToFileFlag:false];
if ([self shouldDisplaySpeechDoneCallbacks])
NSRunAlertPanel(@"Speech Done", @"Generation of synthesized speech is finished.", @"OK", NULL, NULL);
}
/*----------------------------------------------------------------------------------------
displayTextDoneAlert
Displays an alert in response to a text done callback.
----------------------------------------------------------------------------------------*/
- (void)displayTextDoneAlert
{
OSErr theErr = noErr;
unsigned long alertButtonClicked;
// Tell engine to pause while we display this dialog.
theErr = PauseSpeechAt(fCurSpeechChannel, kImmediate);
if (theErr != noErr)
NSRunAlertPanel(@"PauseSpeechAt", [NSString stringWithFormat:@"Error #%d returned.", theErr], @"Oh?", NULL, NULL);
// Display error alert, and stop or continue based on user's desires
alertButtonClicked = NSRunAlertPanel(@"Text Done Callback", @"Processing of the text has completed.", @"Stop", NULL, @"Continue");
if (alertButtonClicked == 1)
[self startStopButtonPressed:fStartStopButton];
else
{
theErr = ContinueSpeech(fCurSpeechChannel);
if (theErr != noErr)
NSRunAlertPanel(@"ContinueSpeech", [NSString stringWithFormat:@"Error #%d returned.", theErr], @"Oh?", NULL, NULL);
}
}
/*----------------------------------------------------------------------------------------
startStopButtonPressed:
An action method called when the user clicks the "Start Speaking"/"Stop Speaking"
button. We either start or stop speaking based on the current speaking state.
----------------------------------------------------------------------------------------*/
- (IBAction)startStopButtonPressed:(id)sender
{
OSErr theErr = noErr;
if (fCurrentlySpeaking) {
long whereToStop;
// Grab where to stop at value from radio buttons
if ([fAfterWordRadioButton intValue])
whereToStop = kEndOfWord;
else if ([fAfterSentenceRadioButton intValue])
whereToStop = kEndOfSentence;
else
whereToStop = kImmediate;
if (whereToStop == kImmediate) {
// NOTE: We could just call StopSpeechAt with kImmediate, but for test purposes
// we exercise the StopSpeech routine.
theErr = StopSpeech(fCurSpeechChannel);
if (theErr != noErr)
NSRunAlertPanel(@"StopSpeech", [NSString stringWithFormat:@"Error #%d returned.", theErr], @"Oh?", NULL, NULL);
}
else {
theErr = StopSpeechAt(fCurSpeechChannel, whereToStop);
if (theErr != noErr)
NSRunAlertPanel(@"StopSpeechAt", [NSString stringWithFormat:@"Error #%d returned.", theErr], @"Oh?", NULL, NULL);
}
fCurrentlySpeaking = false;
[self updateSpeakingControlState];
}
else {
[self startSpeakingTextViewToURL:NULL];
}
}
/*----------------------------------------------------------------------------------------
saveAsButtonPressed:
An action method called when the user clicks the "Save As File" button. We ask user
to specify where to save the file, then start speaking to this file.
----------------------------------------------------------------------------------------*/
- (IBAction)saveAsButtonPressed:(id)sender
{
NSURL * selectedFileURL = NULL;
NSSavePanel * theSavePanel = [NSSavePanel new];
[theSavePanel setPrompt:NSLocalizedString(@"Save", @"Save")];
if (NSFileHandlingPanelOKButton == [theSavePanel runModalForDirectory:NULL file:@"Synthesized Speech.aiff"]) {
selectedFileURL = [theSavePanel URL];
[self startSpeakingTextViewToURL:selectedFileURL];
}
[theSavePanel autorelease];
}
/*----------------------------------------------------------------------------------------
startSpeakingTextViewToURL:
This method sets up the speech channel and begins the speech synthesis
process, optionally speaking to a file instead playing through the speakers.
----------------------------------------------------------------------------------------*/
- (void)startSpeakingTextViewToURL:(NSURL *)url
{
OSErr theErr = noErr;
NSString * theViewText;
// Grab the selection substring, or if no selection then grab entire text.
fOrgSelectionRange = [fSpokenTextView selectedRange];
if (fOrgSelectionRange.length == 0) {
theViewText = [fSpokenTextView string];
fOffsetToSpokenText = 0;
}
else {
theViewText = [[fSpokenTextView string] substringWithRange:fOrgSelectionRange];
fOffsetToSpokenText = fOrgSelectionRange.location;
}
// Setup our callbacks
fSavingToFile = (url != NULL);
if (theErr == noErr) {
theErr = SetSpeechInfo(fCurSpeechChannel, soErrorCallBack, fSavingToFile?NULL:OurErrorCallBackProc);
if (theErr != noErr)
NSRunAlertPanel(@"SetSpeechInfo(soErrorCallBack)", [NSString stringWithFormat:@"Error #%d returned.", theErr], @"Oh?", NULL, NULL);
}
if (theErr == noErr) {
theErr = SetSpeechInfo(fCurSpeechChannel, soPhonemeCallBack, fSavingToFile?NULL:OurPhonemeCallBackProc);
if (theErr != noErr)
NSRunAlertPanel(@"SetSpeechInfo(soPhonemeCallBack)", [NSString stringWithFormat:@"Error #%d returned.", theErr], @"Oh?", NULL, NULL);
}
if (theErr == noErr) {
theErr = SetSpeechInfo(fCurSpeechChannel, soSpeechDoneCallBack, OurSpeechDoneCallBackProc);
if (theErr != noErr)
NSRunAlertPanel(@"SetSpeechInfo(soSpeechDoneCallBack)", [NSString stringWithFormat:@"Error #%d returned.", theErr], @"Oh?", NULL, NULL);
}
if (theErr == noErr) {
theErr = SetSpeechInfo(fCurSpeechChannel, soSyncCallBack, fSavingToFile?NULL:OurSyncCallBackProc);
if (theErr != noErr)
NSRunAlertPanel(@"SetSpeechInfo(soSyncCallBack)", [NSString stringWithFormat:@"Error #%d returned.", theErr], @"Oh?", NULL, NULL);
}
if (theErr == noErr) {
theErr = SetSpeechInfo(fCurSpeechChannel, soTextDoneCallBack, fSavingToFile?NULL:OurTextDoneCallBackProc);
if (theErr != noErr)
NSRunAlertPanel(@"SetSpeechInfo(soTextDoneCallBack)", [NSString stringWithFormat:@"Error #%d returned.", theErr], @"Oh?", NULL, NULL);
}
if (theErr == noErr) {
theErr = SetSpeechInfo(fCurSpeechChannel, soWordCallBack, fSavingToFile?NULL:OurWordCallBackProc);
if (theErr != noErr)
NSRunAlertPanel(@"SetSpeechInfo(soWordCallBack)", [NSString stringWithFormat:@"Error #%d returned.", theErr], @"Oh?", NULL, NULL);
}
// Set URL to save file to disk
SetSpeechInfo(fCurSpeechChannel, 'opaf', url); // Use selector constant soOutputToFileWithCFURL with 10.3 or later
// Convert NSString to cString.
char * theTextToSpeak = (char *)[theViewText lossyCString];
if (theTextToSpeak) {
// We want the text view the active view. Also saves any parameters currently being edited.
[fWindow makeFirstResponder:fSpokenTextView];
OSErr theErr = SpeakText(fCurSpeechChannel, theTextToSpeak, strlen(theTextToSpeak));
if (theErr == noErr) {
// Update our vars
fLastErrorCode = 0;
fLastSpeakingValue = false;
fLastPausedValue = false;
fCurrentlySpeaking = true;
fCurrentlyPaused = false;
[self updateSpeakingControlState];
}
else {
NSRunAlertPanel(@"SpeakText", [NSString stringWithFormat:@"Error #%d returned.", theErr], @"Oh?", NULL, NULL);
}
}
[self enableCallbackControlsBasedOnSavingToFileFlag:fSavingToFile];
}
/*----------------------------------------------------------------------------------------
pauseContinueButtonPressed:
An action method called when the user clicks the "Pause Speaking"/"Continue Speaking"
button. We either pause or continue speaking based on the current speaking state.
----------------------------------------------------------------------------------------*/
- (IBAction)pauseContinueButtonPressed:(id)sender
{
OSErr theErr = noErr;
if (fCurrentlyPaused) {
// We want the text view the active view. Also saves any parameters currently being edited.
[fWindow makeFirstResponder:fSpokenTextView];
theErr = ContinueSpeech(fCurSpeechChannel);
if (theErr != noErr)
NSRunAlertPanel(@"ContinueSpeech", [NSString stringWithFormat:@"Error #%d returned.", theErr], @"Oh?", NULL, NULL);
fCurrentlyPaused = false;
[self updateSpeakingControlState];
}
else {
long whereToPause;
// Figure out where to stop from radio buttons
if ([fAfterWordRadioButton intValue])
whereToPause = kEndOfWord;
else if ([fAfterSentenceRadioButton intValue])
whereToPause = kEndOfSentence;
else
whereToPause = kImmediate;
theErr = PauseSpeechAt(fCurSpeechChannel, whereToPause);
if (theErr != noErr)
NSRunAlertPanel(@"PauseSpeechAt", [NSString stringWithFormat:@"Error #%d returned.", theErr], @"Oh?", NULL, NULL);
fCurrentlyPaused = true;
[self updateSpeakingControlState];
}
}
/*----------------------------------------------------------------------------------------
voicePopupSelected:
An action method called when the user selects a new voice from the Voices pop-up
menu. We ask the speech channel to use the selected voice. If the current
speech channel cannot use the selected voice, we close and open new speech
channel with the selecte voice.
----------------------------------------------------------------------------------------*/
- (IBAction) voicePopupSelected:(id)sender
{
OSErr theErr = noErr;
VoiceSpec theVoiceSpec;
long theSelectedMenuIndex = [sender indexOfSelectedItem];
if (theSelectedMenuIndex == 0) {
//
// Use the default voice from preferences.
//
// Our only choice is to close and reopen the speech channel to get the default voice.
fSelectedVoiceCreator = 0;
theErr = [self createNewSpeechChannel:NULL];
}
else {
//
// Use the voice the user selected.
//
theErr = GetIndVoice([sender indexOfSelectedItem] - 1, &theVoiceSpec);
if (theErr != noErr)
NSRunAlertPanel(@"GetIndVoice", [NSString stringWithFormat:@"Error #%d returned.", theErr], @"Oh?", NULL, NULL);
if (theErr == noErr) {
// Update our object fields with the selection
fSelectedVoiceCreator = theVoiceSpec.creator;
fSelectedVoiceID = theVoiceSpec.id;
// Change the current voice. If it needs another engine, then dispose the current channel and open another
if (SetSpeechInfo(fCurSpeechChannel, soCurrentVoice, &theVoiceSpec) == incompatibleVoice)
theErr = [self createNewSpeechChannel:&theVoiceSpec];
}
}
// Set editable default fields
if (fCurSpeechChannel)
[self fillInEditableParameterFields];
}
/*----------------------------------------------------------------------------------------
charByCharCheckboxSelected:
An action method called when the user checks/unchecks the Character-By-Character
mode checkbox. We tell the speech channel to use this setting.
----------------------------------------------------------------------------------------*/
- (IBAction)charByCharCheckboxSelected:(id)sender
{
OSErr theErr = noErr;
OSType theMode;
if ([fCharByCharCheckboxButton intValue])
theMode = modeLiteral;
else
theMode = modeNormal;
theErr = SetSpeechInfo(fCurSpeechChannel, soCharacterMode, &theMode);
if (theErr != noErr)
NSRunAlertPanel(@"SetSpeechInfo(soCharacterMode)", [NSString stringWithFormat:@"Error #%d returned.", theErr], @"Oh?", NULL, NULL);
}
/*----------------------------------------------------------------------------------------
digitByDigitCheckboxSelected:
An action method called when the user checks/unchecks the Digit-By-Digit
mode checkbox. We tell the speech channel to use this setting.
----------------------------------------------------------------------------------------*/
- (IBAction)digitByDigitCheckboxSelected:(id)sender
{
OSErr theErr = noErr;
OSType theMode;
if ([fDigitByDigitCheckboxButton intValue])
theMode = modeLiteral;
else
theMode = modeNormal;
theErr = SetSpeechInfo(fCurSpeechChannel, soNumberMode, &theMode);
if (theErr != noErr)
NSRunAlertPanel(@"SetSpeechInfo(soNumberMode)", [NSString stringWithFormat:@"Error #%d returned.", theErr], @"Oh?", NULL, NULL);
}
/*----------------------------------------------------------------------------------------
digitByDigitCheckboxSelected:
An action method called when the user checks/unchecks the Phoneme input
mode checkbox. We tell the speech channel to use this setting.
----------------------------------------------------------------------------------------*/
- (IBAction)phonemeModeCheckboxSelected:(id)sender
{
OSErr theErr = noErr;
OSType theMode;
if ([fPhonemeModeCheckboxButton intValue])
theMode = modePhonemes;
else
theMode = modeText;
theErr = SetSpeechInfo(fCurSpeechChannel, soInputMode, &theMode);
if (theErr != noErr)
NSRunAlertPanel(@"SetSpeechInfo(soInputMode)", [NSString stringWithFormat:@"Error #%d returned.", theErr], @"Oh?", NULL, NULL);
}
/*----------------------------------------------------------------------------------------
dumpPhonemesSelected:
An action method called when the user clicks the Dump Phonemes button. We ask
the speech channel for a phoneme representation of the window text then save the
result to a text file at a location determined by the user.
----------------------------------------------------------------------------------------*/
- (IBAction)dumpPhonemesSelected:(id)sender
{
NSSavePanel *panel = [NSSavePanel savePanel];
if ([panel runModal]) {
long theNumOfPhonBytes = 0;
// Get and speech text
char * theTextToSpeak = (char *)[[fSpokenTextView string] lossyCString];
if (theTextToSpeak) {
Handle thePhonemeHandle = NewHandle(0);
if (thePhonemeHandle) {
OSErr theErr = TextToPhonemes(fCurSpeechChannel, (Ptr)theTextToSpeak, (long)strlen(theTextToSpeak), thePhonemeHandle, (long *)&theNumOfPhonBytes);
if (theErr != noErr)
NSRunAlertPanel(@"TextToPhonemes", [NSString stringWithFormat:@"Error #%d returned.", theErr], @"Oh?", NULL, NULL);
else {
// Create NSData object with resulting handle and then write to disk.
NSData * thePhonemeText = [NSData dataWithBytesNoCopy:*thePhonemeHandle length:theNumOfPhonBytes freeWhenDone:false];
if(! [thePhonemeText writeToURL:[panel URL] atomically:false])
NSRunAlertPanel(@"TextToPhonemes", @"Phoneme file could not be written to disk", @"Oh?", NULL, NULL);
}
DisposeHandle(thePhonemeHandle);
}
else
NSRunAlertPanel(@"TextToPhonemes", @"Could not allocate handle for phonemes", @"Oh?", NULL, NULL);
}
}
}
/*----------------------------------------------------------------------------------------
useDictionarySelected:
An action method called when the user clicks the Use Dictionary button.
----------------------------------------------------------------------------------------*/
- (IBAction)useDictionarySelected:(id)sender
{
// Open file.
NSOpenPanel *panel = [NSOpenPanel openPanel];
[panel setAllowsMultipleSelection:YES];
if ([panel runModal]) {
NSEnumerator * fileURLsEnumerator = [[panel URLs]objectEnumerator];
NSURL * fileURL = NULL;
while (fileURL = [fileURLsEnumerator nextObject]) {
// Read dictionary file into NSData object.
NSData * speechSynthesisDictionaryData = [NSData dataWithContentsOfURL:fileURL];
if (speechSynthesisDictionaryData) {
// Allocate handle, then copy the data into the handle and pass it to UseDictionary.
Handle theFileDataHandle = NewHandle([speechSynthesisDictionaryData length]);
if (theFileDataHandle) {
memcpy(*theFileDataHandle, [speechSynthesisDictionaryData bytes], [speechSynthesisDictionaryData length]);
OSErr theErr = UseDictionary(fCurSpeechChannel, theFileDataHandle);
DisposeHandle(theFileDataHandle);
if (theErr != noErr)
NSRunAlertPanel(@"UseDictionary", [NSString stringWithFormat:@"Error #%d returned.", theErr], @"Oh?", NULL, NULL);
}
else
NSRunAlertPanel(@"TextToPhonemes", @"Could not allocate handle for dictionary", @"Oh?", NULL, NULL);
}
else
NSRunAlertPanel(@"TextToPhonemes", [NSString stringWithFormat:@"Error occurred reading %@.", [fileURL path]], @"Oh?", NULL, NULL);
}
}
}
/*----------------------------------------------------------------------------------------
rateChanged:
An action method called when the user changes the rate field. We tell the speech
channel to use this setting.
----------------------------------------------------------------------------------------*/
- (IBAction)rateChanged:(id)sender