iOS开发<记录> 文字转语音iOS10

导入框架:

  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(@"---播放取消");
  }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.ios高性能编程 (1).内层 最小的内层平均值和峰值(2).耗电量 高效的算法和数据结构(3).初始化时...
    欧辰_OSR阅读 29,869评论 8 265
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,671评论 19 139
  • 今天早上,6:50的闹钟声准时响起,而我还在睡梦中挣扎。其实并没有做梦,心里空空如也。 当我敏感的神经还是一下子就...
    清源泉阅读 3,369评论 0 0
  • 爱需要氧气, 我需要你, 但我缺少了想你的勇气。 当我的泪飘落海角天涯时, 而你的缩影却总能勾起我想你的回忆! 你...
    绎文阅读 1,735评论 0 0
  • 余生未必有你们,但我愿把你们写进诗里,祝福你们…… 陈女多才艺 墨云自变晴 祎碧洁无暇 …… 白玉酒一杯 不...
    董小东阅读 3,821评论 14 11