iOS AVSpeechSynthesizer 语音合成

1.基本使用


-(void)initAVSpeechSynthesizer{
  NSString *string = @"Hello, World!";
  //创建发声对象
  AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:string];
 //发音语言中文zh-CN
  utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"en-US"];
  utterance.rate=0.5;// 设置语速,范围0-1,注意0最慢,1最快;AVSpeechUtteranceMinimumSpeechRate最慢,AVSpeechUtteranceMaximumSpeechRate最快
  utterance.volume = 1.0;//音量
  //创建合成对象
  AVSpeechSynthesizer *speechSynthesizer = [[AVSpeechSynthesizer alloc] init];
  //开启合成播放
  [speechSynthesizer speakUtterance:utterance];
}

#pragma mark AVSpeechSynthesizerDelegate

- (void)speechSynthesizer:(AVSpeechSynthesizer*)synthesizer didStartSpeechUtterance:(AVSpeechUtterance*)utterance{
 
}

- (void)speechSynthesizer:(AVSpeechSynthesizer*)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance*)utterance{
    
}

- (void)speechSynthesizer:(AVSpeechSynthesizer*)synthesizer didPauseSpeechUtterance:(AVSpeechUtterance*)utterance{
    
}

- (void)speechSynthesizer:(AVSpeechSynthesizer*)synthesizer didContinueSpeechUtterance:(AVSpeechUtterance*)utterance{
    
}

- (void)speechSynthesizer:(AVSpeechSynthesizer*)synthesizer didCancelSpeechUtterance:(AVSpeechUtterance*)utterance{

}

2.后台运行

1.配置info.plist文件添加音频后台:Add on target's info.plist the key "Required background modes" to "App plays audio or streams audio/video using AirPlay".
2.还要在APPdelegate或者viewDidload或者其他合适地方添加以下代码开启后台播放

NSError *error = NULL;AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:&error];
if(error) { // Do some error handling
}
[session setActive:YES error:&error];
if (error) { // Do some error handling
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容