导入框架:
import <AVFoundation/AVFoundation.h>
创建
@interface ViewController ()<AVSpeechSynthesizerDelegate>
{
AVSpeechSynthesizer * av;
}
添加按钮
/语言播放
UIButton*button=[UIButton buttonWithType:UIButtonTypeCustom];
button.frame=CGRectMake(100,100,100,50);
[button setTitle:@"讲"forState:UIControlStateNormal];
[button setTitle:@"停"forState:UIControlStateSelected];
[button setTitleColor:[UIColor blueColor]forState:UIControlStateNormal];
button.backgroundColor=[UIColor grayColor];
button.showsTouchWhenHighlighted=YES;
[button addTarget:self action:@selector(start:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
设置代理并且实现
-(void)start:(UIButton*)sender{
if(sender.selected==NO) {
if([av isPaused]) {
//如果暂停则恢复,会从暂停的地方继续
[av continueSpeaking];
sender.selected=!sender.selected;
}else{
//初始化对象
av= [[AVSpeechSynthesizer alloc]init];
av.delegate=self;//代理
AVSpeechUtterance*utterance = [[AVSpeechUtterance alloc]initWithString:@"英语文章 How To Cover Your Tracks On The Internet2008-06-25 所属栏目:Security Website Security - Creating a Bulletproof Site in 5 Easy Steps 2008-06"];//需要转换的文字
utterance.rate=0.5;// 设置语速,范围0-1,注意0最慢,1最快;
AVSpeechSynthesisVoice*voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];//设置发音,这是中文普通话
utterance.voice= voice;
[av speakUtterance:utterance];//开始
sender.selected=!sender.selected;
}
}else{
[av pauseSpeakingAtBoundary:AVSpeechBoundaryWord];//暂停
sender.selected=!sender.selected;
}
}
- (void)speechSynthesizer:(AVSpeechSynthesizer*)synthesizer didStartSpeechUtterance:(AVSpeechUtterance*)utterance{
NSLog(@"---开始播放");
}
- (void)speechSynthesizer:(AVSpeechSynthesizer*)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance*)utterance{
NSLog(@"---完成播放");
}
- (void)speechSynthesizer:(AVSpeechSynthesizer*)synthesizer didPauseSpeechUtterance:(AVSpeechUtterance*)utterance{
NSLog(@"---播放中止");
}
- (void)speechSynthesizer:(AVSpeechSynthesizer*)synthesizer didContinueSpeechUtterance:(AVSpeechUtterance*)utterance{
NSLog(@"---恢复播放");
}
- (void)speechSynthesizer:(AVSpeechSynthesizer*)synthesizer didCancelSpeechUtterance:(AVSpeechUtterance*)utterance{
NSLog(@"---播放取消");
}
网友评论