iOS AVSpeechSynthesizer语音合成

2018-05-10  本文已影响3人  倪大头

需要用到AVFoundation框架,AVSpeechUtterance类可以设置语音的语速,语种,音量,延迟等

UITextField *myTextField = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, kScaleX*300, kScaleY*40)];
myTextField.center = CGPointMake(UI_SCREEN_WIDTH/2, kScaleY*300 + myTextField.frame.size.height/2);
myTextField.placeholder = @" 输入一段文字";
myTextField.textColor = [UIColor blackColor];
myTextField.font = [UIFont systemFontOfSize:15];
myTextField.layer.borderColor = [UIColor lightGrayColor].CGColor;
myTextField.layer.borderWidth = 1;
[self.view addSubview:myTextField];
    
UIButton *commitBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, kScaleX*100, kScaleY*40)];
commitBtn.center = CGPointMake(myTextField.center.x, CGRectGetMaxY(myTextField.frame) + kScaleY*20 + commitBtn.frame.size.height/2);
[commitBtn setTitle:@"语音" forState:UIControlStateNormal];
[commitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
commitBtn.titleLabel.font = [UIFont systemFontOfSize:13];
commitBtn.backgroundColor = [UIColor orangeColor];
[self.view addSubview:commitBtn];
[[commitBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
    NSLog(@"%@",myTextField.text);
    self.synthesizer = [[AVSpeechSynthesizer alloc]init];
    self.synthesizer.delegate = self;
    AVSpeechUtterance *utterange = [[AVSpeechUtterance alloc]initWithString:myTextField.text];
    utterange.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];//语言
    utterange.rate = 0.4f;//语速
    //utterange.volume = 1.0f;//音量
    //utterange.pitchMultiplier = 0.7f;//声调 [0.5 - 2] Default = 1
    //utterange.postUtteranceDelay = 0.1;//每句读完之后的延迟
    [self.synthesizer speakUtterance:utterange];
}];

遵循AVSpeechSynthesizerDelegate可以监听语音合成状态,如开始播放/播放结束等

- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didStartSpeechUtterance:(AVSpeechUtterance *)utterance {
    NSLog(@"开始播放");
}
WechatIMG9.png
上一篇下一篇

猜你喜欢

热点阅读