【Demo】iOS平台上的讯飞语音识别语音合成开发

本文介绍如何在iOS应用中集成讯飞语音SDK,包括语音合成与语音测评功能的实现过程。通过实例演示了如何初始化应用、配置参数及处理回调等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

官方文档:http://www.xfyun.cn/doccenter/iOS

目前开放的服务:



准备工作

  • 需要到讯飞官网注册一个开发账号,注册后登录并创建一个新的应用,添加需要的服务(语音听写、语音合成等等),应用创建后可以得到一个Appid,这个要在开发中初始化讯飞语音应用中用到。

  • 工程中找到Targets->Build Phases->Link Binary With Libraries,添加下面的库,注意iflyMSC.framework下载后一定要保证导入到工程目录下,而不能只是个路径引用否则会报错。另外需要在Build Settings的Build Options中关闭BitCode。

  • 在需要的地方引入讯飞语音库头文件,当然可以根据需要只引入某种服务的头文件

#import <iflyMSC/iflyMSC.h> // 引入讯飞语音库
#ifndef MSC_IFlyMSC_h
#define MSC_IFlyMSC_h

#import "IFlyAudioSession.h"
#import "IFlyContact.h"
#import "IFlyDataUploader.h"
#import "IFlyDebugLog.h"
#import "IFlyISVDelegate.h"
#import "IFlyISVRecognizer.h"
#import "IFlyRecognizerView.h"
#import "IFlyRecognizerViewDelegate.h"
#import "IFlyResourceUtil.h"
#import "IFlySetting.h"
#import "IFlySpeechConstant.h"
#import "IFlySpeechError.h"
#import "IFlySpeechEvaluator.h"
#import "IFlySpeechEvaluatorDelegate.h"
#import "IFlySpeechEvent.h"
#import "IFlySpeechRecognizer.h"
#import "IFlySpeechRecognizerDelegate.h"
#import "IFlySpeechSynthesizer.h"
#import "IFlySpeechSynthesizerDelegate.h"
#import "IFlySpeechUnderstander.h"
#import "IFlySpeechUtility.h"
#import "IFlyTextUnderstander.h"
#import "IFlyUserWords.h"
#import "IFlyPcmRecorder.h"
#import "IFlyVoiceWakeuper.h"
#import "IFlyVoiceWakeuperDelegate.h"

#endif
  • 使用Appid初始化讯飞应用,在应用启动的地方使用Appid初始化语音应用,这里放在了AppDelegate应用代理文件下:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    NSString *initString = [[NSString alloc] initWithFormat:@"appid=%@",@"587f6174"];
    [IFlySpeechUtility createUtility:initString];
    return YES;
}

语音合成和语音测评示例

这里因为要使用语音合成和测评功能所以先测试了这两个,其他的类似,可参考官方文档:

  • 应用启动后会有‘小燕’的声音读出:”Hello, this is xiaoyan!”
  • 应用启动后测评”Today is a sunny day!”的发音

先要使用Appid初始化:
这里写图片描述

//
//  ViewController.m
//  XFDemo
//
//  Created by Xinhou Jiang on 4/3/17.
//  Copyright © 2017年 Xinhou Jiang. All rights reserved.
//

#import "ViewController.h"
#import <iflyMSC/iflyMSC.h> // 引入讯飞语音库

@interface ViewController ()<IFlySpeechSynthesizerDelegate,IFlySpeechEvaluatorDelegate> { // 语音代理协议

}
@property (nonatomic, strong)IFlySpeechSynthesizer *iFlySpeechSynthesizer;    // 定义语音合成对象
@property (nonatomic, strong)IFlySpeechEvaluator *iFlySpeechEvaluator;        // 定义语音测评对象

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 1.开始合成说话
    //[self.iFlySpeechSynthesizer startSpeaking:@"Hello, this is xiaoyan!"];

    // 2.开始语音测评
    NSData *textData = [@"Today is a sunny day!" dataUsingEncoding:NSUTF8StringEncoding];
    [self.iFlySpeechEvaluator startListening:textData params:nil];
}

#pragma -mark 语音合成
/**
 * 懒加载getter方法
 */
- (IFlySpeechSynthesizer *)iFlySpeechSynthesizer {
    if(!_iFlySpeechSynthesizer) {
    // 初始化语音合成
    _iFlySpeechSynthesizer = [IFlySpeechSynthesizer sharedInstance];
    _iFlySpeechSynthesizer.delegate = self;
    // 语速【0-100】
    [_iFlySpeechSynthesizer setParameter:@"50" forKey:[IFlySpeechConstant SPEED]];
    // 音量【0-100】
    [_iFlySpeechSynthesizer setParameter:@"50" forKey:[IFlySpeechConstant VOLUME]];
    // 发音人【小燕:xiaoyan;小宇:xiaoyu;凯瑟琳:catherine;亨利:henry;玛丽:vimary;小研:vixy;小琪:vixq;小峰:vixf;小梅:vixl;小莉:vixq;小蓉(四川话):vixr;小芸:vixyun;小坤:vixk;小强:vixqa;小莹:vixying;小新:vixx;楠楠:vinn;老孙:vils】
    [_iFlySpeechSynthesizer setParameter:@"xiaoyan" forKey:[IFlySpeechConstant VOICE_NAME]];
    // 音频采样率【8000或16000】
    [_iFlySpeechSynthesizer setParameter:@"8000" forKey:[IFlySpeechConstant SAMPLE_RATE]];
    // 保存音频路径(默认在Document目录下)
    [_iFlySpeechSynthesizer setParameter:@"tts.pcm" forKey:[IFlySpeechConstant TTS_AUDIO_PATH]];
    }
    return _iFlySpeechSynthesizer;
}

/**
 * 合成结束
 */
- (void)onCompleted:(IFlySpeechError *)error {
    NSLog(@"合成结束!");
}

/**
 * 合成开始
 */
- (void)onSpeakBegin {
    NSLog(@"合成开始!");
}

/**
 * 合成缓冲进度【0-100】
 */
- (void)onBufferProgress:(int)progress message:(NSString *)msg {
    NSLog(@"合成缓冲进度:%d/100",progress);
}

/**
 * 合成播放进度【0-100】
 */
- (void)onSpeakProgress:(int)progress beginPos:(int)beginPos endPos:(int)endPos {
    NSLog(@"合成播放进度:%d/100",progress);
}

#pragma -mark 语音测评
/**
 * 懒加载getter方法
 */
- (IFlySpeechEvaluator *)iFlySpeechEvaluator {
    if (!_iFlySpeechEvaluator) {
        // 初始化语音测评
        _iFlySpeechEvaluator = [IFlySpeechEvaluator sharedInstance];
        _iFlySpeechEvaluator.delegate = self;
        // 设置测评语种【中文:zh_cn,中文台湾:zh_tw,美英:en_us】
        [_iFlySpeechEvaluator setParameter:@"en_us" forKey:[IFlySpeechConstant LANGUAGE]];
        // 设置测评题型【read_syllable(英文评测不支持):单字;read_word:词语;read_sentence:句子;read_chapter(待开放):篇章】
        [_iFlySpeechEvaluator setParameter:@"read_sentence" forKey:[IFlySpeechConstant ISE_CATEGORY]];
        // 设置试题编码类型
        [_iFlySpeechEvaluator setParameter:@"utf-8" forKey:[IFlySpeechConstant TEXT_ENCODING]];
        // 设置前、后端点超时【0-10000(单位ms)】
        [_iFlySpeechEvaluator setParameter:@"10000" forKey:[IFlySpeechConstant VAD_BOS]]; // 默认5000ms
        [_iFlySpeechEvaluator setParameter:@"1000" forKey:[IFlySpeechConstant VAD_EOS]]; // 默认1800ms
        // 设置录音超时,设置成-1则无超时限制(单位:ms,默认30000)
        [_iFlySpeechEvaluator setParameter:@"5000" forKey:[IFlySpeechConstant SPEECH_TIMEOUT]];
        // 设置结果等级,不同等级对应不同的详细程度【complete:完整 ;plain:简单】
        [_iFlySpeechEvaluator setParameter:@"" forKey:[IFlySpeechConstant ISE_RESULT_LEVEL]];
    }
    return _iFlySpeechEvaluator;
}

/**
 * 开始说话回调
 */
- (void)onBeginOfSpeech {
    NSLog(@"开始说话...");
}

/**
 * 说话结束回调
 */
- (void)onEndOfSpeech {
    NSLog(@"说话结束...");
}

/**
 * 测评结果
 */
- (void)onResults:(NSData *)results isLast:(BOOL)isLast {
    NSLog(@"测评结果:%@",results);
}

/**
 * 出错回调
 */
- (void)onError:(IFlySpeechError *)errorCode {
    NSLog(@"语音测评出错:%@",errorCode);
}

/**
 * 音量变化回调
 */
- (void)onVolumeChanged:(int)volume buffer:(NSData *)buffer {
    NSLog(@"音量变化...");
}

/**
 * 取消
 */
- (void)onCancel {
    NSLog(@"正在取消...");
}

@end

Demo 下载:https://github.com/jiangxh1992/XFSpeechDemo

2 预备工作 2.1 创建iOS工程 在XCode中建立你的工程,或者打开已经建立的工程。 2.2 添加静态库 将开发工具包中lib目录下的iflyMSC.framework添加到新建工程中(如下图所示)。 提交 图一 图二 提交 图三 2.3 添加framework 按下图添加SDK所需要的iOS库,请注意libz.dylib,CoreTelephoney.framework不要遗漏。 提交 图四 注:如果使用的是离线识别,还需要增加libc++.dylib。 2.4 确认SDK的路径 提交 图五 请确认上图红色部分的路径能够找到iflyMSC.framework。为了支持多人开发,建议双击红色部分,把路径改为相对路径,例如像下图所示。 提交 图六 注意:请把不必要的路径删除。例如更新了SDK后,新的SDK与旧的SDK不在同一路径,请把旧的路径删除,避免引用到旧的库。对应集成SDK后发现编译失败,提示找不到头文件,请先检查这个路径是否正确。 2.5 导入头文件 在你需要使用MSC服务的文件中导入相应的头文件 例如: C/C++ Code //带界面的语音识别控件 #import “iflyMSC/IFlyRecognizerViewDelegate.h” #import “iflyMSC/IFlyRecognizerView.h” C/C++ Code //不带界面的语音识别控件 #import “iflyMSC/IFlySpeechRecognizerDelegate.h” #import “iflyMSC/IFlySpeechRecognizer.h” C/C++ Code //不带界面的语音合成控件 #import “iflyMSC/IFlySpeechSynthesizerDelegate.h” #import “iflyMSC/IFlySpeechSynthesizer.h” 2.6 集成帮助文档到Xcode 打开终端(termainl或iterm),cd 到压缩包的doc 目录,执行以下命令: 注:不同的xcode版本,对应的docset路径可能有变化,需要根据实际路径来操作。 C/C++ Code cp -R -f -a com.iflytek.documentation.IFlyMSC.docset ~/Library/Developer/Shared/Documentation/DocSets/ 然后执行命令 C/C++ Code open ~/Library/Developer/Shared/Documentation/DocSets/ 请核对文档的版本为最新下载的版本 提交 图七 打开Xcode的帮助文档就可以看到已经集成的文档 提交 图八 2.7 初始化 必须在初始化后才可以使用语音服务,初始化是异步过程,推荐在程序入口处调用。 Appid是应用的身份信息,具有唯一性,初始化时必须要传入Appid。可以从demo的Definition.h APPID_VALUE中查看此信息。Demo和SDK申请地址:http://xfyun.cn C/C++ Code //将“12345678”替换成您申请的APPID。 NSString *initString = [[NSString alloc] initWithFormat:@"appid=%@",@” 12345678”]; [IFlySpeechUtility createUtility:initString]; 3 语音听写 使用示例如下: C/C++ Code //头文件定义 //需要实现IFlyRecognizerViewDelegate,为识别会话的服务代理 @interface RecognizerViewController : UIViewController<IFlyRecognizerViewDelegate> { IFlyRecognizerView *_iflyRecognizerView; } //初始化语音识别控件 _iflyRecognizerView = [[IFlyRecognizerView alloc] initWithCenter:self.view.center]; _iflyRecognizerView.delegate = self; [_iflyRecognizerView setParameter: @"iat" forKey: [IFlySpeechConstant IFLY_DOMAIN]]; //asr_audio_path保存录音文件名,如不再需要,设置value为nil表示取消,默认目录是documents [_iflyRecognizerView setParameter:@"asrview.pcm " forKey:[IFlySpeechConstant ASR_AUDIO_PATH]]; //启动识别服务 [_iflyRecognizerView start]; /*识别结果返回代理 @param resultArray 识别结果 @ param isLast 表示是否最后一次结果 */ - (void)onResult: (NSArray *)resultArray isLast:(BOOL) isLast { } /*识别会话错误返回代理 @ param error 错误码 */ - (void)onError: (IFlySpeechError *) error { } 4 语音识别 4.1 在线语音识别 上传联系人,使用示例如下: C/C++ Code //创建上传对象 _uploader = [[IFlyDataUploader alloc] init]; //获取联系人集合 IFlyContact *iFlyContact = [[IFlyContact alloc] init]; NSString *contactList = [iFlyContact contact]; //设置参数 [_uploader setParameter:@"uup" forKey:@"subject"]; [_uploader setParameter:@"contact" forKey:@"dtt"]; //启动上传 [_uploader uploadDataWithCompletionHandler:^(NSString * grammerID, IFlySpeechError *error) { //接受返回的grammerID和error [self onUploadFinished:grammerID error:error]; }name:@"contact" data: contactList]; 上传用户词表,使用示例如下: C/C++ Code //创建上传对象 _uploader = [[IFlyDataUploader alloc] init]; //生成用户词表对象 //用户词表 #define USERWORDS @"{\"userword\":[{\"name\":\"iflytek\",\"words\":[\"德国盐猪手\",\"1912酒吧街\",\"清蒸鲈鱼\",\"挪威三文鱼\",\"黄埔军校\",\"横沙牌坊\",\"科大\"]}]}" IFlyUserWords *iFlyUserWords = [[IFlyUserWords alloc] initWithJson:USERWORDS ]; #define NAME @"userwords" //设置参数 [_uploader setParameter:@"iat" forKey:@"sub"]; [_uploader setParameter:@"userword" forKey:@"dtt"]; //上传词表 [_uploader uploadDataWithCompletionHandler:^(NSString * grammerID, IFlySpeechError *error) { //接受返回的grammerID和error [self onUploadFinished:grammerID error:error]; } name:NAME data:[iFlyUserWords toString]]; abnf语法上传,示例如下: C/C++ Code // ABNF语法示例,可以说”北京到上海” #define ABNFPARAM @”sub=asr,dtt=abnf” #define ABNFDATA = “#ABNF 1.0 gb2312; language zh-CN; mode voice; root $main; $main = $place1 到$place2 ; $place1 = 北京 | 武汉 | 南京 | 天津 | 天京 | 东京; $place2 = 上海 | 合肥;” //创建上传对象 _uploader = [[IFlyDataUploader alloc] init]; //设置参数 [_uploader setParameter:@"asr" forKey:@"sub"]; [_uploader setParameter:@"abnf" forKey:@"dtt"]; //上传abnf语法 [_uploader uploadDataWithCompletionHandler:^(NSString * grammerID, IFlySpeechError *error) { //接受返回的grammerID和error [self setGrammerId:grammerID]; }name:ABNFNAME data:ABNFDATA]; 4.2 本线语音识别 1) 创建识别对象(注:如果使用的是离线识别,还需要增加libc++.dylib) C/C++ Code //此方法为demo中封装,具体实现请参照demo。 self.iFlySpeechRecognizer = [RecognizerFactory CreateRecognizer:self Domain:@"asr"]; 2)设置参数 C/C++ Code //开启候选结果 [_iflySpeechRecognizer setParameter:@"1" forKey:@"asr_wbest"]; //设置引擎类型,clound或者local [_iflySpeechRecognizer setParameter:@”local” forKey:[IFlySpeechConstant ENGINE_TYPE]]; //设置字符编码为utf-8 [_iflySpeechRecognizer setParameter:@"utf-8" forKey:[IFlySpeechConstant TEXT_ENCODING]]; //语法类型,本地是bnf,在线识别是abnf [_iflySpeechRecognizer setParameter:@”bnf” forKey:[IFlyResourceUtil GRAMMARTYPE]]; //启动asr识别引擎 [[IFlySpeechUtility getUtility] setParameter:@"asr" forKey:[IFlyResourceUtil ENGINE_START]]; //设置服务类型为asr识别 [_iflySpeechRecognizer setParameter:@"asr" forKey:[IFlySpeechConstant IFLY_DOMAIN]]; //设置语法构建路径,该路径为sandbox下的目录,请确保目录存在 [_iflySpeechRecognizer setParameter:_grammBuildPath forKey:[IFlyResourceUtil GRM_BUILD_PATH]]; //设置引擎资源文件路径,如demo中的aitalkResource中的common.mp3 [_iflySpeechRecognizer setParameter:_aitalkResourcePath forKey:[IFlyResourceUtil ASR_RES_PATH]]; 3)编译语法文本
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mr_厚厚

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值