荼蘼
荼蘼
  • 发布:2016-11-24 17:34
  • 更新:2024-06-20 17:47
  • 阅读:5067

iOS讯飞语音自定义界面

分类:5+ SDK

MUI的人没空回答只能看他们的插件源码自己写了,废话不多说代码如下:

JS脚本 xfyun-plugin.js文件  
;define(function(require, exports, module) {  
    var _BARCODE = 'XFYunPlugin',  
        B = window.plus.bridge;  

    var XFYunPlugin =   
    {  
        /**  
         * 开始语音识别  
         */  
        startListen : function (successCallback, errorCallback)  
        {  
            var success = typeof successCallback !== 'function' ? null : function(args)   
            {  
                successCallback(args);  
            },  
            fail = typeof errorCallback !== 'function' ? null : function(code)   
            {  
                errorCallback(code);  
            };  
            callbackID = B.callbackId(success, fail);  

            return B.exec(_BARCODE, "startListen", [callbackID]);  
        },  

        /**  
         * 停止语音识别  
         */  
        stopListen : function (successCallback, errorCallback)  
        {  
            var success = typeof successCallback !== 'function' ? null : function(args)   
            {  
                successCallback(args);  
            },  
            fail = typeof errorCallback !== 'function' ? null : function(code)   
            {  
                errorCallback(code);  
            };  
            callbackID = B.callbackId(success, fail);  

            return B.exec(_BARCODE, "stopListen", [callbackID]);  
        }  
    };  
    window.plus.XFYunPlugin = XFYunPlugin;  
});  

原生插件  
PGNXFYunPlugin.h文件  

#include "PGPlugin.h"  
#include "PGMethod.h"  
#import <Foundation/Foundation.h>  

// 讯飞  
#import "iflyMSC/IFlySpeechRecognizerDelegate.h"  
#import "iflyMSC/IFlySpeechRecognizer.h"  
#import "iflyMSC/IFlySpeechConstant.h"  
#import "iflyMSC/IFlySpeechError.h"  

@interface PGXFYunPlugin : PGPlugin<IFlySpeechRecognizerDelegate>  
{  
    IFlySpeechRecognizer *iflySpeechRecognizer;  
}  

@property(nonatomic, strong)NSString *callBackID;  
@property (nonatomic, assign) BOOL isSpeeching; // 是否正在录音  

// 开始语音识别  
- (void)startListen:(PGMethod *)command;  

// 停止语音识别  
- (void)stopListen:(PGMethod *)command;  

@end  

PGNXFYunPlugin.m文件  

#import "PGXFYunPlugin.h"  

@implementation PGXFYunPlugin  

@synthesize callBackID;  
@synthesize isSpeeching;  

// 开始语音识别  
- (void)startListen:(PGMethod *)command  
{  

    if (command && !self.isSpeeching) {  
        // CallBackid 异步方法的回调id,H5+ 会根据回调ID通知JS层运行结果成功或者失败  
        NSString *cbId = [command.arguments objectAtIndex:0];  

        self.callBackID = cbId;  
        self.isSpeeching = YES;  

        // 创建语音听写对象  
        if (iflySpeechRecognizer == nil) {  
            iflySpeechRecognizer = [IFlySpeechRecognizer sharedInstance];  
            [iflySpeechRecognizer setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];  

            // 设置听写参数  
            [iflySpeechRecognizer setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];  
            //asr_audio_path保存录音文件名,如不再需要,设置value为nil表示取消,默认目录是Library/cache  
            [iflySpeechRecognizer setParameter:nil forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];  
            //设置最长录音时间12s  
            [iflySpeechRecognizer setParameter:@"12000" forKey:[IFlySpeechConstant SPEECH_TIMEOUT]];  
            //网络等待时间30s  
            [iflySpeechRecognizer setParameter:@"20000" forKey:[IFlySpeechConstant NET_TIMEOUT]];  
            //设置是否返回标点符号  
            [iflySpeechRecognizer setParameter:@"0" forKey:[IFlySpeechConstant ASR_PTT]];  
        }  
        iflySpeechRecognizer.delegate = self;  

        // 启动识别服务  
        [iflySpeechRecognizer startListening];  

    }  

}  

// 停止语音识别  
- (void)stopListen:(PGMethod *)command {  
    if (command) {  

        self.isSpeeching = NO;  
        if (iflySpeechRecognizer != nil) {  
            // 停止识别服务  
            [iflySpeechRecognizer stopListening];  

        }  

    }  
}  

#pragma mark IFlySpeechRecognizerDelegate.h delegate  

/*  
 识别结果返回代理  
*/  
- (void)onResults:(NSArray *)results isLast:(BOOL)isLast  
{  
    NSLog(@"onResults");  

    self.isSpeeching = NO;  

    if (self.callBackID != nil) {  

        NSMutableString *resultMutableString = [[NSMutableString alloc] init];  
        NSDictionary *dic = results[0];  
        for (NSString *key in dic) {  
            [resultMutableString appendFormat:@"%@",key];  
        }  
        NSString *resultString = [NSString stringWithFormat:@"%@", resultMutableString];  
        NSString *resultFromJson =  [self stringFromJson:resultString];  

        NSDictionary *dicResult = [NSDictionary dictionaryWithObjectsAndKeys:  
                                   @"type",   @"text",  
                                   @"value", resultFromJson,  
                                   nil];  

        // 运行Native代码结果和预期相同,调用回调通知JS层运行成功并返回结果  
        PDRPluginResult *result = [PDRPluginResult resultWithStatus:PDRCommandStatusOK messageAsDictionary:dicResult];  

        // 通知JS层Native层运行结果,JS Pluginbridge会根据cbid找到对应的回调方法并触发  
        [self toCallback:self.callBackID withReslut:[result toJSONString]];  
    }  

}  

/*  
 识别会话结束返回代理 (注:无论听写是否正确都会回调)  
 error.errorCode =  
 0     听写正确  
 other 听写出错  
 */  
- (void) onError:(IFlySpeechError *) error  
{  
    NSLog(@"onError");  

    self.isSpeeching = NO;  

    if (error.errorCode != 0 && self.callBackID != nil ) {  

        NSDictionary *dicResult = [NSDictionary dictionaryWithObjectsAndKeys:  
                                   @"code", [NSString stringWithFormat:@"%d", error.errorCode],  
                                   @"desc", error.errorDesc,  
                                   nil];  

        // 如果Native代码运行结果和预期不同,需要通过回调通知JS层出现错误,并返回错误提示  
        PDRPluginResult *result = [PDRPluginResult resultWithStatus:PDRCommandStatusError messageAsDictionary:dicResult];  

        // 通知JS层Native层运行结果,JS Pluginbridge会根据cbid找到对应的回调方法并触发  
        [self toCallback:self.callBackID withReslut:[result toJSONString]];  
    }  

}  

/*  
 开始录音回调  
 */  
- (void)onBeginOfSpeech  
{  
    NSLog(@"onBeginOfSpeech");  
}  

/*  
 停止录音回调  
*/  
- (void)onEndOfSpeech  
{  
    NSLog(@"onEndOfSpeech");  

    self.isSpeeching = NO;  
}  

/*  
 音量回调函数  
 volume 0-30  
 */  
- (void)onVolumeChanged:(int)volume  
{  
    if (self.callBackID != nil ) {  

        NSDictionary *dicResult = [NSDictionary dictionaryWithObjectsAndKeys:  
                                   @"type",   @"volume",  
                                   @"value", [NSString stringWithFormat:@"%d", volume],  
                                   nil];  

        // 运行Native代码结果和预期相同,调用回调通知JS层运行成功并返回结果  
        PDRPluginResult *result = [PDRPluginResult resultWithStatus:PDRCommandStatusOK messageAsDictionary: dicResult];  

        // 通知JS层Native层运行结果,JS Pluginbridge会根据cbid找到对应的回调方法并触发  
        [self toCallback:self.callBackID withReslut:[result toJSONString]];  
    }  
}  

- (void)dealloc {  
    [super dealloc];  

    [iflySpeechRecognizer cancel]; //取消识别  
    [iflySpeechRecognizer setDelegate:nil];  
    [iflySpeechRecognizer setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];  

    self.callBackID = nil;  
    self.isSpeeching = nil;  
}  

/**  
 解析听写json格式的数据  
 params例如:  
 {"sn":1,"ls":true,"bg":0,"ed":0,"ws":[{"bg":0,"cw":[{"w":"白日","sc":0}]},{"bg":0,"cw":[{"w":"依山","sc":0}]},{"bg":0,"cw":[{"w":"尽","sc":0}]},{"bg":0,"cw":[{"w":"黄河入海流","sc":0}]},{"bg":0,"cw":[{"w":"。","sc":0}]}]}  
 ****/  
- (NSString *)stringFromJson:(NSString*)params  
{  
    if (params == NULL) {  
        return nil;  
    }  

    NSMutableString *tempStr = [[NSMutableString alloc] init];  
    NSDictionary *resultDic  = [NSJSONSerialization JSONObjectWithData:    //返回的格式必须为utf8的,否则发生未知错误  
                                [params dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];  

    if (resultDic!= nil) {  
        NSArray *wordArray = [resultDic objectForKey:@"ws"];  

        for (int i = 0; i < [wordArray count]; i++) {  
            NSDictionary *wsDic = [wordArray objectAtIndex: i];  
            NSArray *cwArray = [wsDic objectForKey:@"cw"];  

            for (int j = 0; j < [cwArray count]; j++) {  
                NSDictionary *wDic = [cwArray objectAtIndex:j];  
                NSString *str = [wDic objectForKey:@"w"];  
                [tempStr appendString: str];  
            }  
        }  
    }  
    return tempStr;  
}  

@end  

// 调用方法  
plus.XFYunPlugin.startListen(function(result) {  
// 成功回调函数  
JSON.stringify(result);  
}, function(error) {  
// 失败回调函数  
JSON.stringify(error);  
});  
3 关注 分享
赵梦欢 androidjdx 6***@qq.com

要回复文章请先登录注册

androidjdx

androidjdx

大佬, [IFlySpeechRecognizer onError:] [IN] errorCode=10111 请问这是啥错误啊? 没有初始化改怎么办
2017-07-11 13:36
androidjdx

androidjdx

大佬,请问这个文件PGPlugin.h是在哪里找到的
2017-07-06 10:40