我在我的 iOS 应用程序中使用 AVSpeechSynthesizer 进行 TTS。但是没有调用 didFinishSpeechUtterance 方法。
这是我在 .h 中的代码:
#import <AVFoundation/AVFoundation.h>
@interface EmailViewController : UIViewController <UITextFieldDelegate, AVSpeechSynthesizerDelegate>
@property (nonatomic, strong) AVSpeechSynthesizer* talker;
这是在.m
- (void) startTalking {
NSString *hi = [NSString stringWithFormat:@"%@", humanLanguageArray[speaknumber]];
AVSpeechUtterance* utter = [[AVSpeechUtterance alloc] initWithString:hi];
utter.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"en-US"];
[utter setRate:0.2f];
if (!self.talker) {
self.talker = [AVSpeechSynthesizer new];
}
self.talker.delegate = self;
[self.talker speakUtterance:utter];
}
- (void)stopSpeech
{
AVSpeechSynthesizer *talked = [[AVSpeechSynthesizer alloc] init];
if([talked isSpeaking]) {
[talked stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:@""];
[talked speakUtterance:utterance];
[talked stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
}
}
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance *)utteranc
{
if (speaknumber < (length-1)) {
speaknumber += 1;
self.talker.delegate = self;
NSString *hi = [NSString stringWithFormat:@"%@", humanLanguageArray[speaknumber]];
AVSpeechUtterance *utter = [[AVSpeechUtterance alloc] initWithString:hi];
utter.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"en-US"];
[utter setRate:0.2f];
if (!self.talker) {
self.talker = [AVSpeechSynthesizer new];
}
[self.talker speakUtterance:utter];
} else if (speaknumber >= length) {
}
}
如果我调用 stopSpeech,它不会停止说话,它会一直说话直到
speaknumber >= length
。有谁知道如何解决这一问题? 最佳答案
为什么要再次在 stopSpeech 中实例化 AVSpeechSynthesizer?
- (void)stopSpeech
{
AVSpeechSynthesizer *talked = self.talker;
if([talked isSpeaking]) {
[talked stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:@""];
[talked speakUtterance:utterance];
[talked stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
}
}
说话的实例是 self.talker,不是吗?