導(dǎo)入框架:
import <AVFoundation/AVFoundation.h>
創(chuàng)建
@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];
設(shè)置代理并且實現(xiàn)
-(void)start:(UIButton*)sender{
if(sender.selected==NO) {
if([av isPaused]) {
//如果暫停則恢復(fù)带到,會從暫停的地方繼續(xù)
[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"];//需要轉(zhuǎn)換的文字
utterance.rate=0.5;// 設(shè)置語速沽讹,范圍0-1科吭,注意0最慢,1最快;
AVSpeechSynthesisVoice*voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];//設(shè)置發(fā)音授舟,這是中文普通話
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(@"---恢復(fù)播放");
}
- (void)speechSynthesizer:(AVSpeechSynthesizer*)synthesizer didCancelSpeechUtterance:(AVSpeechUtterance*)utterance{
NSLog(@"---播放取消");
}