1.概述
語音合成是將一段文字轉換為成語音,可根據需要合成出不同音色、語速和語調的聲音,讓機器像人一樣開口說話。
第一步:獲取appid
登錄訊飛開放平臺(https://passport.xfyun.cn/login),創建應用獲取APPid
第二步:工程配置
訊飛不支持CocoaPods,只能手動導入配置文件,其中iflyMSC.framework是從官方網站獲取(我的應用-點擊應用-語音合成-在線語音合成(流式版)SDK下載)。將開發工具包中lib目錄下的iflyMSC.framework添加到工程中。其他配置文件如下圖:
配置文件圖.png
第三步:設置Bitcode
MSC SDK暫時還不支持Bitcode,可以先臨時關閉。后續MSC SDK支持Bitcode 時,會在訊飛開放平臺上進行SDK版本更新,請關注。關閉此設置,只需在Targets - Build Settings 中搜索Bitcode 即可,找到相應選項,設置為NO。
Bitcode關閉.png
第四步:代碼
1.AppDelegate 進行初始化
//配置語音識別
//Set log level
/*!
* 設置日志msc.log生成路徑以及日志等級
*
* | 日志打印等級 | 描述 |
* |------------------------|-----------------------------------|
* | LVL_ALL | 全部打印 |
* | LVL_DETAIL | 高,異常分析需要的級別 |
* | LVL_NORMAL | 中,打印基本日志信息 |
* | LVL_LOW | 低,只打印主要日志信息 |
* | LVL_NONE | 不打印 |
*
* @param level -[in] 日志打印等級
*/
[IFlySetting setLogFile:LVL_NONE];
//Set whether to output log messages in Xcode console
/*!
* 是否打印控制臺log<br>
* 在軟件發布時,建議關閉此log。
*
* @param showLog -[in] YES,打印log;NO,不打印
*/
[IFlySetting showLogcat:YES];
// 初始化訊飛應用
NSString *initString = [[NSString alloc] initWithFormat:@"appid=%@",kXunFeiKey];
[IFlySpeechUtility createUtility:initString];
2.播放代碼
IFlySpeechSynthesizer * iFlySpeechSynthesizer = [IFlySpeechSynthesizer sharedInstance];
self.iFlySpeechSynthesizer = iFlySpeechSynthesizer;
iFlySpeechSynthesizer.delegate = self;
// 語速【0-100】
[iFlySpeechSynthesizer setParameter:@"50" forKey:[IFlySpeechConstant SPEED]];
// 音量【0-100】
[iFlySpeechSynthesizer setParameter:@"50" forKey:[IFlySpeechConstant VOLUME]];
// 發音人默認xiaoyan
[iFlySpeechSynthesizer setParameter:@"xiaoyan" forKey:[IFlySpeechConstant VOICE_NAME]];
// 音頻采樣率【8000或16000】
[iFlySpeechSynthesizer setParameter:@"16000" forKey:[IFlySpeechConstant SAMPLE_RATE]];
// 保存音頻路徑(默認在Document目錄下)
[iFlySpeechSynthesizer setParameter:@"tts.pcm" forKey:[IFlySpeechConstant TTS_AUDIO_PATH]];
//文本編碼格式
[iFlySpeechSynthesizer setParameter:@"unicode" forKey:[IFlySpeechConstant TEXT_ENCODING]];
[self.iFlySpeechSynthesizer startSpeaking:@"北京-上海"];
#pragma mark --- 語音合成代理方法
/**
* 合成緩沖進度【0-100】
*/
- (void)onBufferProgress:(int)progress message:(NSString *)msg {
NSLog(@"合成緩沖進度:%d/100",progress);
}
/**
* 合成開始
*/
- (void)onSpeakBegin {
NSLog(@"合成播放開始!");
}
/**
* 合成播放進度【0-100】
*/
- (void)onSpeakProgress:(int)progress beginPos:(int)beginPos endPos:(int)endPos {
NSLog(@"合成播放進度:%d/100",progress);
}
/**
* 合成結束
*/
- (void)onCompleted:(IFlySpeechError *)error {
NSLog(@"合成結束!");
}
需要注意的是:
SDK與APPID是綁定的,一個APPID對應一個SDK。否則會報 報錯誤碼10407。
新申請了新的APPID,Framework Search Path里要引用新SDK。
完整代碼GitHub