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
}