苹果公司在iOS7中推出了语音合成的技术,无需网络环境也可以实现语音合成。
iOS7语音合成的主要的API如下:
1、AVSpeechUtterance,是语音合成的基本单位,它封装影响语音合成的需要的一些参数:语音、语调、语速和延迟等。
2、AVSpeechSynthesisVoice,是语音合成中的Voice对象,它主要包括语音和地区两个方面。
3、AVSpeechSynthesizer,语音合成器的管理类,通过speakUtterance:方法管理AVSpeechSynthesizer。
4、AVSpeechSynthesizerDelegate,是AVSpeechSynthesizer的委托协议。
代码如下:
#import "DemoVC36.h"
#import
@interface DemoVC36 ()@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (weak, nonatomic) IBOutlet UISlider *slider;
@property (nonatomic, strong) AVSpeechSynthesizer *speechSynthesizer;
@end
@implementation DemoVC36
- (void)viewDidLoad {
[super viewDidLoad];
//为TextView
[self.textView.layer setBorderWidth:0.5f];
[self.textView.layer setBorderColor:[UIColor grayColor].CGColor];
[self.textView setDelegate:self];
self.speechSynthesizer = [[AVSpeechSynthesizer alloc] init];
self.speechSynthesizer.delegate = self;
}
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
BOOL retval = TRUE;
if ([text isEqualToString:@"\n"]) {
[self.textView resignFirstResponder];
retval = FALSE;
}
return retval;
}
- (IBAction)speakButtonWasPressed:(UIButton *)sender {
NSString *str = @"wei fang is a handsome man";
AVSpeechUtterance *utt = [AVSpeechUtterance speechUtteranceWithString:str];
utt.rate = [self.slider value];
[self.speechSynthesizer speakUtterance:utt];
}
- (IBAction)speechSpeedShouldChange:(id)sender {
UISlider *slider = (UISlider *)sender;
NSInteger val = round(slider.value);
NSLog(@"%@",[NSString stringWithFormat:@"%ld",val]);
}
#pragma mark--AVSpeechSynthesizerDelegate
-(void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didStartSpeechUtterance:(AVSpeechUtterance *)utterance{
NSLog(@"语音合成开始");
}
-(void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance *)utterance{
NSLog(@"语音合成完成");
}
@end