首先,文字转语音最简单的方案就是使用系统提供的接口
一、AVSpeechSynthesizer
AVSpeechSynthesizer开放的接口数量少,很难满足我们开发的各种需求,这个时候第三方的语音就是我们比较好的选择。。
文本转语音技术, 也叫TTS, 是Text To Speech的缩写. iOS如果想做有声书等功能的时候, 会用到这门技术.
iOS7之后才有该功能
需要 AVFoundation 库
AVSpeechSynthesizer: 语音合成器, 可以假想成一个可以说话的人, 是最主要的接口
AVSpeechSynthesisVoice: 可以假想成人的声音
AVSpeechUtterance: 可以假想成要说的一段话
二、百度语音包
百度语音,我选择的是百度语音包!(尽管百度一直狠招黑)
2.1下载离线合成语音包
2.2记住这3个key(说多了都是泪,后来才知道AppId就是AppCode,杀千刀的文档)
2.3给出的demo还是十分打的,我在自己精简了很多主要是实现播放和设置声音
-(void)configureSDK{
NSLog(@"TTS version info: %@", [BDSSpeechSynthesizer version]);
[BDSSpeechSynthesizer setLogLevel:BDS_PUBLIC_LOG_VERBOSE];
[[BDSSpeechSynthesizer sharedInstance] setSynthesizerDelegate:self];
[self configureOnlineTTS];
[self configureOfflineTTS];
}
// 配置在线
-(void)configureOnlineTTS{
//#error "Set api key and secret key"
[[BDSSpeechSynthesizer sharedInstance] setApiKey:@"e7QA3FWob8EbzLDP7I6fCtcY" withSecretKey:@"17d90e1974d0bcb31725245f96718e73"];
}
// 配置离线
-(void)configureOfflineTTS{
NSString* offlineEngineSpeechData = [[NSBundle mainBundle] pathForResource:@"Chinese_Speech_Female" ofType:@"dat"];
NSString* offlineEngineTextData = [[NSBundle mainBundle] pathForResource:@"Chinese_Text" ofType:@"dat"];
NSString* offlineEngineEnglishSpeechData = [[NSBundle mainBundle] pathForResource:@"English_Speech_Female" ofType:@"dat"];
NSString* offlineEngineEnglishTextData = [[NSBundle mainBundle] pathForResource:@"English_Text" ofType:@"dat"];
NSString* offlineEngineLicenseFile = [[NSBundle mainBundle] pathForResource:@"offline_engine_tmp_license" ofType:@"dat"];
//#error "set offline engine license"
NSError* err = [[BDSSpeechSynthesizer sharedInstance] loadOfflineEngine:offlineEngineTextData speechDataPath:offlineEngineSpeechData licenseFilePath:offlineEngineLicenseFile withAppCode:@"9353239"]; //
if (err) {
return;
}
err = [[BDSSpeechSynthesizer sharedInstance] loadEnglishDataForOfflineEngine:offlineEngineEnglishTextData speechData:offlineEngineEnglishSpeechData];
if (err) {
return;
}
}
// 播放失败
-(void)synthesizerErrorOccurred:(NSError *)error speaking:(NSInteger)SpeakSentence synthesizing:(NSInteger)SynthesizeSentence{
[[BDSSpeechSynthesizer sharedInstance] cancel];
}
// 合成参数设置
// 声音
[[BDSSpeechSynthesizer sharedInstance] setSynthesizerParam:[NSNumber numberWithInt:BDS_SYNTHESIZER_SPEAKER_FEMALE] forKey:BDS_SYNTHESIZER_PARAM_SPEAKER ];
// 音量
[[BDSSpeechSynthesizer sharedInstance] setSynthesizerParam:[NSNumber numberWithInt:5] forKey:BDS_SYNTHESIZER_PARAM_VOLUME];
// 音速
[[BDSSpeechSynthesizer sharedInstance] setSynthesizerParam:[NSNumber numberWithInt:5] forKey:BDS_SYNTHESIZER_PARAM_SPEED];
// 音调
[[BDSSpeechSynthesizer sharedInstance] setSynthesizerParam:[NSNumber numberWithInt:5] forKey:BDS_SYNTHESIZER_PARAM_PITCH];
// 压缩
[[BDSSpeechSynthesizer sharedInstance] setSynthesizerParam:[NSNumber numberWithInt: BDS_SYNTHESIZER_AUDIO_ENCODE_MP3_16K] forKey:BDS_SYNTHESIZER_PARAM_AUDIO_ENCODING ];