標籤:
蘋果公司在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
iOS語音合成