29,027
社区成员
发帖
与我相关
我的任务
分享
#import <Cocoa/Cocoa.h>
@interface ViewController : NSViewController
{
NSSpeechSynthesizer* _speechSynth;
}
- (IBAction)stopIt:(id)sender;
- (IBAction)sayIt:(id)sender;
@property (weak) IBOutlet NSTextField *textField;
@end
#import "ViewController.h"
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)setRepresentedObject:(id)representedObject {
[super setRepresentedObject:representedObject];
// Update the view, if already loaded.
}
- (id)init {
self = [super init];
if (self) {
// Logs can help the beginner understand what
// is happening and hunt down bugs.
NSLog(@"init");
// Create a new instance of NSSpeechSynthesizer
// with the default voice.
_speechSynth = [[NSSpeechSynthesizer alloc] initWithVoice:@"com.apple.speech.synthesis.voice.Alex"];
}
return self;
}
- (IBAction)stopIt:(id)sender {
NSLog(@"stopping");
[_speechSynth stopSpeaking];
}
- (IBAction)sayIt:(id)sender {
NSString *string = [_textField stringValue];
// Is the string zero-length?
if ([string length] == 0) {
NSLog(@"string from %@ is of zero-length", _textField);
return; }
// _speechSynth = [[NSSpeechSynthesizer alloc] initWithVoice:nil];
// [_speechSynth setVoice:@"com.apple.speech.synthesis.voice.Alex"];
[_speechSynth startSpeakingString:string];
while([NSSpeechSynthesizer isAnyApplicationSpeaking] == true) {}
NSLog(@"Have started to say: %@", string);
}
@end