作用:
用文本转化成语音。例如输入文本“hello world",则系统语音读出来
前提引入
#import <AVFoundation/AVFoundation.h>
/**
核心代码
*/
-(void)func_textToVoice
{
NSLog(@"开始转化语音");
//要转化的文本
NSString * text = self.array_text[0];
//语言配置类
AVSpeechUtterance * utterance = [[AVSpeechUtterance alloc]initWithString:text];
utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CH"];
//TODO...
//语音合成器
[self.synthesizer speakUtterance:utterance];
}
批量转化语音
/**
多条文本转换语音
*/
-(void)func_moreTextsToVoice
{
self.array_text = @[
@"除夕更阑人不睡,厌禳钝滞迎新岁;",
@"小儿呼叫走长街,云有痴呆召人买。",
@"二物于人谁独无?就中吴侬仍有余;",
@"巷南巷北卖不得,相逢大笑相揶揄。",
@"栎翁块坐重帘下,独要买添令问价。",
@"儿云翁买不须钱,奉赊痴呆千百年。",
];
for(int i=0;i<self.array_text.count;i++)
{
AVSpeechUtterance * utterance = [[AVSpeechUtterance alloc]initWithString:array_text[i]];
utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];
// utterance.postUtteranceDelay = 0.1f;
// utterance.preUtteranceDelay = 0.5f;
utterance.pitchMultiplier = 0.8f;
//TODO...
[self.synthesizer speakUtterance:utterance];
}
}
设置语言属性,如音调、前后延迟间隔、语速、音量等
/**
个性化配置语音
*/
-(void)func_configVoice
{
//要转化的文本
NSString * text = self.array_text[0];
//语言配置类
AVSpeechUtterance * utterance = [[AVSpeechUtterance alloc]initWithString:text];
//定制语种
utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CH"];
//定制基线音调,范围0.5~2.0,默认1.0
utterance.pitchMultiplier = 1.0;
//定制语速,建议用常量来控制范围 AVSpeechUtteranceMinimumSpeechRate AVSpeechUtteranceMaximumSpeechRate AVSpeechUtteranceDefaultSpeechRate.
utterance.rate = AVSpeechUtteranceDefaultSpeechRate;
//定制音量
utterance.volume = 1.0;
//该语音播放完后延迟时间再播放下一个
utterance.postUtteranceDelay = 0.5f;
//等待延迟时间再进行播放
utterance.preUtteranceDelay = 0.1;
//TODO...
//语音合成器
[self.synthesizer speakUtterance:utterance];
}
语音合成事件协议
#pragma AVSpeechSynthesizerDelegate
-(void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didStartSpeechUtterance:(AVSpeechUtterance *)utterance
{
NSLog(@"语音合成开始");
}
-(void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didPauseSpeechUtterance:(AVSpeechUtterance *)utterance
{
NSLog(@"语音合成暂停");
}
-(void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didCancelSpeechUtterance:(AVSpeechUtterance *)utterance
{
NSLog(@"语音合成取消");
}
-(void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance *)utterance
{
NSLog(@"语音合成完成");
}
-(void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer willSpeakRangeOfSpeechString:(NSRange)characterRange utterance:(AVSpeechUtterance *)utterance
{
NSLog(@"语音合成即将播放第%lu个字长度为%lu",(unsigned long)characterRange.location,(unsigned long)characterRange.length);
}
暂停
/**
暂停语音播放
*/
-(void)func_pauseVoice
{
if(self.synthesizer.speaking)
{
[self.synthesizer pauseSpeakingAtBoundary:AVSpeechBoundaryImmediate];//立即停止
[self.synthesizer pauseSpeakingAtBoundary:AVSpeechBoundaryWord];//读完停止
}
}
继续
/**
继续播放
*/
-(void)func_continueSpeaking
{
if(self.synthesizer.paused)
{
[self.synthesizer continueSpeaking];
}
}
QQ:384302147
网友评论