Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: dde81ed01d
Fetching contributors…

Cannot retrieve contributors at this time

file 634 lines (478 sloc) 15.005 kb
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
//
// UKSpeechSynthesizer.m
// UKSpeechSynthesizer
//
// Created by Uli Kusterer on Mon Jun 30 2003.
// Copyright (c) 2003 M. Uli Kusterer. Uli Kusterer
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//

/* -----------------------------------------------------------------------------
Headers:
-------------------------------------------------------------------------- */

#import <Carbon/Carbon.h>
#import "UKSpeechSynthesizer.h"
#import "UKHelperMacros.h"


/* -----------------------------------------------------------------------------
Constants:
-------------------------------------------------------------------------- */

// This is what we prefix when returning voice identifiers so we're compatible with NSSpeechChannel:
#define UK_SPEECH_VOICE_PREFIX @"com.apple.speech.synthesis.voice."

NSString* const NSSpeechPitchBaseProperty = @"NSSpeechPitchBaseProperty";


/* -----------------------------------------------------------------------------
Prototypes:
-------------------------------------------------------------------------- */

pascal void MyPhonemeCallback( SpeechChannel chan, long refCon, short phonemeOpcode );
pascal void MySpeechDoneCallback( SpeechChannel chan, long refCon );


@interface UKSpeechSynthesizer (PrivateMethods)

-(id) reallocSpeechChannelWithVoice: (VoiceSpec*)spec;
-(void) setPhonemeOpcode: (short)n;
-(void) notifySpeechDoneObject: (id)dummy;
-(void) notifySpeechPhonemeObject: (id)dummy;

@end


@implementation UKSpeechSynthesizer

/* -----------------------------------------------------------------------------
Class methods:
-------------------------------------------------------------------------- */

+(id) speechSynthesizer
{
return [[[self alloc] autorelease] init];
}


+(id) speechSynthesizerWithVoice: (NSString*)voiceName
{
return [[[self alloc] autorelease] initWithVoice: voiceName];
}



+(VoiceSpec) voiceSpecFromVoice: (NSString*)voiceName
{
VoiceSpec spec = { 0 };
short count, x;
VoiceDescription vInfo;

if( CountVoices( &count ) != noErr )
return spec;

NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
for( x = 0; x < count; x++ )
{
if( GetIndVoice( x, &spec ) == noErr )
{
if( GetVoiceDescription( &spec, &vInfo, sizeof(vInfo) ) == noErr )
{
if( [[UK_SPEECH_VOICE_PREFIX stringByAppendingString: [NSString stringWithCString:(char*)(vInfo.name +1) length:(vInfo.name[0])]] isEqualToString:voiceName] )
{
[pool release];
return spec;
}
}
}
}

spec.id = 0; spec.creator = 0;

[pool release];
return spec;
}


+(NSArray*) availableVoices
{
VoiceSpec spec = { 0 };
short count, x;
VoiceDescription vInfo;
NSMutableArray* theArray = [NSMutableArray array];

if( CountVoices( &count ) != noErr )
return nil;

NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
for( x = 0; x < count; x++ )
{
if( GetIndVoice( x, &spec ) == noErr )
{
if( GetVoiceDescription( &spec, &vInfo, sizeof(vInfo) ) == noErr )
[theArray addObject: [UK_SPEECH_VOICE_PREFIX stringByAppendingString: [NSString stringWithCString:(char*)(vInfo.name +1) length:(vInfo.name[0])]]];
}
}

[pool release];
return theArray;
}


+(NSString*) voiceFromVoiceSpec: (VoiceSpec*)spec
{
VoiceDescription vInfo;

if( GetVoiceDescription( spec, &vInfo, sizeof(vInfo) ) == noErr )
{
return( [UK_SPEECH_VOICE_PREFIX stringByAppendingString: [NSString stringWithCString:(char*)(vInfo.name +1) length:(vInfo.name[0])]] );
}
else
return nil;
}


+(NSString*) defaultVoice
{
return[self voiceFromVoiceSpec: NULL];
}


+(NSDictionary*) attributesForVoice:(NSString*)voice
{
VoiceDescription vInfo;
VoiceSpec spec = [self voiceSpecFromVoice: voice];
if( GetVoiceDescription( &spec, &vInfo, sizeof(vInfo) ) == noErr )
{
NSMutableDictionary* dict = [NSMutableDictionary dictionary];
[dict setObject: voice forKey: NSVoiceIdentifier];
[dict setObject: [NSString stringWithCString:(char*)(vInfo.name +1) length:(vInfo.name[0])] forKey: NSVoiceName];
[dict setObject: [NSString stringWithCString:(char*)(vInfo.comment +1) length:(vInfo.comment[0])] forKey: NSVoiceDemoText];
[dict setObject: [NSNumber numberWithShort: vInfo.age] forKey: NSVoiceAge];

NSString* genders[3] = { NSVoiceGenderNeuter,
NSVoiceGenderMale,
NSVoiceGenderFemale };

[dict setObject: genders[vInfo.gender] forKey: NSVoiceGender];
[dict setObject: [NSNumber numberWithShort: vInfo.language] forKey: NSVoiceLanguage];

return dict;
}
else
return nil;
}


+(BOOL) isAnyApplicationSpeaking
{
return SpeechBusySystemWide();
}


/* -----------------------------------------------------------------------------
Instance methods:
-------------------------------------------------------------------------- */

-(id) init
{
if( self = [super init] )
{
speechChannel = nil;
speechPhonemeUPP = speechDoneUPP = nil;
delegate = nil;
buffer = nil;

speechPhonemeUPP = NewSpeechPhonemeUPP( &MyPhonemeCallback );
speechDoneUPP = NewSpeechDoneUPP( &MySpeechDoneCallback );

if( [self reallocSpeechChannelWithVoice: nil] == nil )
return nil;
}
return self;
}

-(id) initWithVoice: (NSString*)voiceName
{
if( self = [super init] )
{
VoiceSpec spec = [UKSpeechSynthesizer voiceSpecFromVoice:voiceName];
speechChannel = nil;
speechPhonemeUPP = speechDoneUPP = nil;
delegate = nil;
buffer = nil;

speechPhonemeUPP = NewSpeechPhonemeUPP( &MyPhonemeCallback );
speechDoneUPP = NewSpeechDoneUPP( &MySpeechDoneCallback );

if( [self reallocSpeechChannelWithVoice: &spec] == nil )
return nil;
}
return self;
}

-(void) dealloc
{
DisposeSpeechChannel( speechChannel );
if( speechDoneUPP != nil )
DisposeSpeechDoneUPP( (SpeechDoneUPP) speechDoneUPP);
if( speechPhonemeUPP != nil )
DisposeSpeechPhonemeUPP( (SpeechPhonemeUPP) speechPhonemeUPP);
if( buffer )
free( buffer );

[super dealloc];
}


- (oneway void)release
{
if( [self retainCount] == 1 )
UKLog(@"UKSpeechChannel released.");
[super release];
}



-(id) reallocSpeechChannelWithVoice: (VoiceSpec*)spec
{
if( speechChannel )
{
DisposeSpeechChannel( speechChannel );
speechChannel = nil;
}

if( NewSpeechChannel( spec, &speechChannel ) != noErr )
return nil;

if( SetSpeechInfo( speechChannel, soRefCon, (Ptr)self ) != noErr ) return nil;
if( SetSpeechInfo( speechChannel, soPhonemeCallBack, speechPhonemeUPP ) != noErr ) return nil;
if( SetSpeechInfo( speechChannel, soSpeechDoneCallBack, speechDoneUPP ) != noErr ) return nil;

if( spec == nil )
{
[currVoice release];
currVoice = [[UKSpeechSynthesizer defaultVoice] retain];
}

return self;
}


-(BOOL) usesFeedbackWindow
{
return usesFeedbackWindow;
}


-(void) setUsesFeedbackWindow: (BOOL)n
{
usesFeedbackWindow = n;
}


-(void) setVoice: (NSString*)voiceName
{
VoiceSpec spec;

if( voiceName == nil )
[self reallocSpeechChannelWithVoice: nil];
else
{
[currVoice release];
currVoice = [voiceName retain];
spec = [UKSpeechSynthesizer voiceSpecFromVoice: voiceName];
[self reallocSpeechChannelWithVoice: &spec];
}
}


-(NSString*) voice
{
return currVoice;
}


-(void) startSpeakingString: (NSString*)str
{
if( isSpeaking )
{
UKLog(@"Stopping previous speech.");
[self stopSpeaking]; // Can't do this unconditionally! It'll send an additional "speech done" callback!
}

if( buffer )
{
free( buffer );
buffer = nil;
}
buffer = malloc( [str cStringLength] +1 );
[str getCString:buffer];

[self retain];

UKLog(@"About to speak: \"%@\"",str);
SpeakText( speechChannel, buffer, strlen(buffer) );
isSpeaking = YES;

if( [str length] == 0 )
{
UKLog(@"Triggering Speech Done Notification because [str length] == 0");
[self notifySpeechDoneObject: nil];
}
}


-(BOOL) isSpeaking
{
return isSpeaking;
}


-(void) stopSpeaking
{
StopSpeech( speechChannel );
}


-(void) stopSpeakingAt: (long)whereToStop
{
StopSpeechAt( speechChannel, whereToStop );
}


-(void) pauseSpeakingAt: (long)whereToStop
{
PauseSpeechAt( speechChannel, whereToStop );
}


-(void) continueSpeaking
{
ContinueSpeech( speechChannel );
}


-(void) setSpeechPitch: (double)pitch
{
SetSpeechPitch( speechChannel, X2Fix( pitch ) );
}


-(double) speechPitch
{
Fixed nb;
GetSpeechPitch( speechChannel, &nb );

return Fix2X( nb );
}

- (id)objectForProperty:(NSString *)property error:(NSError **)outError
{
if( [property isEqualToString: NSSpeechPitchBaseProperty] )
{
if( outError )
*outError = nil;
return [NSNumber numberWithDouble: [self speechPitch]];
}
else
{
if( outError )
*outError = [NSError errorWithDomain: @"UKSpeechSynthesizerErrorDomain" code: 1 userInfo: [NSDictionary dictionary]];
return nil;
}
}


- (BOOL)setObject:(id)object forProperty:(NSString *)property error:(NSError **)outError
{
if( [property isEqualToString: NSSpeechPitchBaseProperty] )
{
if( outError )
*outError = nil;
[self setSpeechPitch: [object doubleValue]];
return YES;
}
else
{
if( outError )
*outError = [NSError errorWithDomain: @"UKSpeechSynthesizerErrorDomain" code: 1 userInfo: [NSDictionary dictionary]];
return NO;
}
}


-(void) setRate: (float)n
{
Fixed vVolume;

vVolume = X2Fix(n);
SetSpeechInfo( speechChannel, soRate, &vVolume );
}


-(float) rate
{
Fixed vVolume;
float n = 0;

if( GetSpeechInfo( speechChannel, soRate, &vVolume ) == noErr )
n = Fix2X( vVolume );

return n;
}


-(void) notifySpeechDoneObject: (id)dummy
{
if( buffer )
{
free( buffer );
buffer = nil;
}
UKLog(@"Speech Done Notification.");

if( isSpeaking )
{
[self release];
isSpeaking = NO;
}
[delegate speechSynthesizer: (NSSpeechSynthesizer*) self didFinishSpeaking: YES];
}


-(void) notifySpeechPhonemeObject: (id)dummy
{
[delegate speechSynthesizer: (NSSpeechSynthesizer*) self willSpeakPhoneme: phonemeOpcode];
}


-(void) setVolume: (float)n
{
Fixed vVolume;

vVolume = X2Fix(n);
SetSpeechInfo( speechChannel, soVolume, &vVolume );
}


-(float) volume
{
Fixed vVolume;
float n = -1;

if( GetSpeechInfo( speechChannel, soVolume, &vVolume ) == noErr )
{
n = Fix2X( vVolume );
}

return n;
}


-(void) setDelegate: (id)delly
{
delegate = delly;
}


-(id) delegate
{
return delegate;
}

-(void) setPhonemeOpcode: (short)n
{
phonemeOpcode = n;
}


-(SpeechChannel) channel
{
return speechChannel;
}

-(NSDictionary*) settingsDictionary
{
NSMutableDictionary* dict = [NSMutableDictionary dictionary];

[dict setObject: [self voice] forKey: @"voice"];
[dict setObject: [NSNumber numberWithInt: [self usesFeedbackWindow]] forKey: @"usesFeedbackWindow"];
[dict setObject: [NSNumber numberWithFloat: [self volume]] forKey: @"speechVolume"];
[dict setObject: [NSNumber numberWithDouble: [self speechPitch]] forKey: @"speechPitch"];
[dict setObject: [NSNumber numberWithFloat: [self rate]] forKey: @"speechRate"];

UKLog(@"speechSettingsDict(OUT) = %@", dict);

return dict;
}


-(void) setSettingsDictionary: (NSDictionary*)dict
{
UKLog(@"speechSettingsDict(IN) = %@",dict);

[self setVoice: [dict objectForKey: @"voice"]];
[self setUsesFeedbackWindow: [[dict objectForKey: @"usesFeedbackWindow"] boolValue]];
[self setVolume: [[dict objectForKey: @"speechVolume"] floatValue]];
[self setSpeechPitch: [[dict objectForKey: @"speechPitch"] doubleValue]];
[self setRate: [[dict objectForKey: @"speechRate"] floatValue]];
}


// Remove any speech commands from the specified string. You can use this for displaying the string being spoken:
+(NSString*) prettifyString: (NSString*)inString
{
NSMutableString* str = [inString mutableCopy];
NSRange commandRange = { 0, 0 },
cmdEndRange;

if( !str )
return str;

while( commandRange.location != NSNotFound || commandRange.length != 0 )
{
commandRange = [str rangeOfString: @"[["];

if( commandRange.location == NSNotFound && commandRange.length == 0 )
break;

cmdEndRange = [str rangeOfString: @"]]"];
if( cmdEndRange.location == NSNotFound && cmdEndRange.length == 0 )
break;

commandRange.length += ((cmdEndRange.location +cmdEndRange.length) -(commandRange.location +commandRange.length));
[str deleteCharactersInRange: commandRange];
}

return str;
}

@end


@implementation NSObject (UKSpeechSynthesizerDelegate)

- (void)speechSynthesizer:(NSSpeechSynthesizer *)sender didFinishSpeaking:(BOOL)finishedSpeaking
{

}


- (void)speechSynthesizer:(NSSpeechSynthesizer *)sender willSpeakPhoneme:(short)phonemeOpcode
{

}


@end




/* --------------------------------------------------------------------------------
MyPhonemeCallback:
Phoneme callback procedure for lip syncronization.
REVISIONS:
2000-11-02 UK Created.
----------------------------------------------------------------------------- */

pascal void MyPhonemeCallback( SpeechChannel chan, long refCon, short phonemeOpcode )
{
CREATE_AUTORELEASE_POOL(pool);
if( [(UKSpeechSynthesizer*)refCon isSpeaking] )
{
UKLog(@"Phoneme %d",phonemeOpcode);
[((UKSpeechSynthesizer*)refCon) setPhonemeOpcode:phonemeOpcode];
[((UKSpeechSynthesizer*)refCon) performSelectorOnMainThread:@selector(notifySpeechPhonemeObject:)
withObject:nil waitUntilDone: NO];
}
else
UKLog(@"Ignoring Phoneme %d which arrived after speech done callback.",phonemeOpcode);
DESTROY(pool);
}


/* --------------------------------------------------------------------------------
MySpeechDoneCallback:
Speech output has ended. Notify the speech channel so it can broadcast a
message that may be used to hide any speech feedback elements or to reset
lip-synched mouths to a default position.
REVISIONS:
2001-08-18 UK Created.
----------------------------------------------------------------------------- */

pascal void MySpeechDoneCallback( SpeechChannel chan, long refCon )
{
CREATE_AUTORELEASE_POOL(pool);
UKLog(@"Sending speech done on main thread.");
//((UKSpeechSynthesizer*)refCon)->isSpeaking = NO;
[((UKSpeechSynthesizer*)refCon) performSelectorOnMainThread:@selector(notifySpeechDoneObject:)
withObject:nil waitUntilDone: NO];
DESTROY(pool);
}
Something went wrong with that request. Please try again.