我正在构建一个应用程序,其中一部分会说出时间。但是,当我将日期字符串(如 10/24/11)传递给 NSSpeechSynthesizer 时,它会按字面意思说出它们,如“一,零,斜线二四斜线一一”,与时间戳相同,“八冒号一一”冒号冒号”等。
我查看了 NSSpeechSynthesizer 文档,我想我必须使用 phonemesFromText 方法,但这似乎需要大量繁重的工作才能让应用程序顺利说出时间和日期。有更快的方法吗?
谢谢
你可以尝试这样的事情:
@implementation MDAppController
- (id)init {
if ((self = [super init])) {
}
return self;
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
NSDateFormatter *dateParser = [[[NSDateFormatter alloc]
initWithDateFormat:@"%m/%d/%y" allowNaturalLanguage:YES] autorelease];
NSDate *date = [dateParser dateFromString:@"10/24/11"];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
NSString *string = [dateFormatter stringFromDate:date];
NSLog(@"string == %@", string);
// prints "October 24, 2011"
NSSpeechSynthesizer *alex = [[NSSpeechSynthesizer alloc]
initWithVoice:[NSSpeechSynthesizer defaultVoice]];
[alex setDelegate:self];
[alex startSpeakingString:string];
}
- (void)speechSynthesizer:(NSSpeechSynthesizer *)sender
didFinishSpeaking:(BOOL)finishedSpeaking {
if (finishedSpeaking) [sender autorelease];
}
@end
Basically, this is using 2 NSDateFormatter
s: one to "translate" the string representation of a date into an actual NSDate
object, and then another to translate that NSDate
back into a more desirable string representation.
Obviously, you'll need to adjust the dateParser
format to fit your expected input string type. (Preferably, you could just use an input date rather than the string representation of it).
为什么不使用NSDateComponents和 -[NSString stringWithFormat:] 构造一个口语句子作为您的字符串,然后说出来?