Cocoa学习笔记(1): 使用NSSpeechSynthesizer朗读
18 Aug 2012
新建Cocoa Application工程,然后添加一个Object-c Class,名字为:AppController。
修改AppController.h 内容,代码如下。
给window设置firstResponser:textField,让它运行即获得输入焦点。
将一个Object拖入Objects窗口:
修改为AppController类:
关联成员变量和动作:
修改AppController.m,代码如下。
运行:
若想了解程序背后运行机制,推荐图书:《Cocoa Programming for Mac OS X 》
我看的是第三版,现在有第四版了貌似。
#import <Foundation/Foundation.h>
@interface AppController : NSObject{
IBOutlet NSTextField *textField;
NSSpeechSynthesizer *speechSynth;
}
- (IBAction)sayIt:(id)sender;
- (IBAction)stopIt:(id)sender;
@end
#import "AppController.h"
@implementation AppController
- (id)init{
NSLog(@"init");
speechSynth=[[NSSpeechSynthesizer alloc] initWithVoice:nil];
return self;
}
- (IBAction)sayIt:(id)sender{
NSString *string=[textField stringValue];
if([string length]==0){
NSLog(@"The textField %@ is of zero-length",textField);
return;
}
[speechSynth startSpeakingString:string];
NSLog(@"Have started to say:%@",string);
}
- (IBAction)stopIt:(id)sender{
[speechSynth stopSpeaking];
NSLog(@"Have stopped");
}
@end


