- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

//创建语音配置,appid必须要传入,仅执行一次则可

NSString *initString = [[NSString alloc] initWithFormat:@"appid=570f3db3"];

//所有服务启动前,需要确保执行createUtility

[IFlySpeechUtility createUtility:initString];

return YES;

}

制作录音文件,使用apple原生API框架。需要添加头文件AVFoundation框架,在程序第一次启用时候会请求是否打开此项功能。另使用科大API只能免费使用在线SDK,调用离线SDK只能用于3个iOS设备使用35天。离线购买价格很贵。

#import "iflyMSC/IFlyMSC.h"

#import "iflyMSC/IFlySpeechConstant.h"

#import "iflyMSC/IFlySpeechRecognizerDelegate.h"

#import "iflyMSC/IFlySpeechRecognizer.h"

@import AVFoundation;

<AVAudioRecorderDelegate>使用代理

@property (nonatomic,strong)IFlySpeechRecognizer *iFlySpeechRecognizer;

@property (nonatomic,strong)AVAudioRecorder *recorder;

@property (nonatomic,strong)AVAudioPlayer *player;

@property (nonatomic,strong)NSTimer *timer;

@property (nonatomic,strong)NSURL *url;

@property (nonatomic,strong)NSMutableDictionary *dict;

@property (nonatomic,strong)UIProgressView *gress;

@property (nonatomic,strong)NSMutableString *text;

@property (weak, nonatomic) IBOutlet UITextField *textField;

AVAudioSession *session = [AVAudioSession sharedInstance];

//单例模式,设置为录音并播放

[session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];

[session setActive:YES error:nil];

NSString *str = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];

self.url = [NSURL fileURLWithPath:[str stringByAppendingPathComponent:@"myFirstRecord.caf"]];

设置文件的保存路径

self.gress = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];

self.gress.progress = 0;设置进度条

self.gress.frame = CGRectMake(90, 200, 200, 2);

[self.view addSubview:self.gress];

self.dict = [NSMutableDictionary dictionary];

[self.dict setObject:@(kAudioFormatLinearPCM) forKey:AVFormatIDKey];

[self.dict setObject:@10000 forKey:AVSampleRateKey];

[self.dict setObject:@1 forKey:AVNumberOfChannelsKey];

[self.dict setObject:@8 forKey:AVLinearPCMBitDepthKey];

[self.dict setObject:@(YES) forKey:AVLinearPCMIsFloatKey];

if (!_recorder) {

_recorder = [[AVAudioRecorder alloc]initWithURL:self.url settings:self.dict error:nil];

_recorder.delegate = self;

_recorder.meteringEnabled = YES;

}

if (!_player) {

_player = [[AVAudioPlayer alloc]initWithContentsOfURL:self.url error:nil];

}

[self start];

- (void)start{

_iFlySpeechRecognizer = [IFlySpeechRecognizer sharedInstance]; //设置听写模式

_iFlySpeechRecognizer.delegate = self;

//2.设置听写参数

[_iFlySpeechRecognizer setParameter: @"iat" forKey: [IFlySpeechConstant IFLY_DOMAIN]];

//asr_audio_path是录音文件名,设置value为nil或者为空取消保存,默认保存目录在 Library/cache下。

[_iFlySpeechRecognizer setParameter:@"asrview.pcm" forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];

//3.启动识别服务 [_iFlySpeechRecognizer start];

}

- (NSTimer *)timer{

if (!_timer) {

_timer = [NSTimer scheduledTimerWithTimeInterval:1/20.0 target:self selector:@selector(showProgress:) userInfo:nil repeats:YES];

NSLog(@"nstime");

}

return _timer;

}

- (void)showProgress:(NSTimer*)t{

[self.recorder updateMeters];

float power = [self.recorder averagePowerForChannel:0];//取得第一个通道的音频,注意音频强度范围时-160到0

self.gress.progress = (power+160)/160.0;

}

- (IBAction)recording:(id)sender {

if (![self.recorder isRecording]) {

[self.recorder record];

self.timer.fireDate = [NSDate distantPast];

}

NSLog(@"录音开始!");

}

- (IBAction)pause:(id)sender {

if (![self.recorder isRecording]) {

[self.recorder pause];

self.timer.fireDate = [NSDate distantFuture];

}else{

[self.recorder record];

self.timer.fireDate = [NSDate distantPast];

}

NSLog(@"暂停切换!");

}

- (IBAction)stop:(id)sender {

[self.recorder stop];

NSLog(@"录音结束!");

self.timer.fireDate = [NSDate distantFuture];

self.timer = nil;

self.gress.progress = 0;

}

- (IBAction)iflyClick:(id)sender {

NSLog(@"iflyClick");按下button的时候调用方法TouchDown

_text = [[NSMutableString alloc]init];

[_iFlySpeechRecognizer startListening];

}

- (IBAction)iflyClickstop:(id)sender {

NSLog(@"iflyClickstop");离开button后调用的方法,无论是在按钮上离开还是在按钮外离开都执行。TouchUpInside&TouchUpOutside

[_iFlySpeechRecognizer stopListening];

}

#pragma  - mark -   AVAudioRecordDelegate

- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{

AVAudioSession *session = [AVAudioSession sharedInstance];

[session setCategory:AVAudioSessionCategoryPlayback error:nil]; //开启扬声器

[session setActive:YES error:nil];

if(![self.player isPlaying]){

[self.player play];

}

NSLog(@"录音完成!");

}

#pragma  - mark -   IFlySpeechRecognizerDelegate

- (void) onError:(IFlySpeechError *) errorCode{

NSLog(@"onError-----------------%@",errorCode);

}

- (void) onResults:(NSArray *) results isLast:(BOOL)isLast{

NSLog(@"onResults-----------------%@",results);

NSMutableString *result = [[NSMutableString alloc] init];

NSDictionary *dic = [results objectAtIndex:0];

for (NSString *key in dic){

[result appendFormat:@"%@",key];//合并结果

}

NSLog(@"result-------%@",result);

NSMutableArray *strArr = [[result componentsSeparatedByString:@"\"}]}"] mutableCopy];

[strArr removeLastObject];

for (NSString *str in strArr) {

[_text appendString:[[str componentsSeparatedByString:@"\""]lastObject]];

}

NSLog(@"_text-------%@",_text);

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

self.textField.text = _text;

});

}

-(void)viewWillDisappear:(BOOL)animated

{

[_iFlySpeechRecognizer cancel];

_iFlySpeechRecognizer.delegate = nil;

//设置回非语义识别

[_iFlySpeechRecognizer destroy];

[super viewWillDisappear:animated];

}

iOS开发之语音功能实现的更多相关文章

  1. IOS开发之支付功能概述

    前言:本随笔将对IOS开发的支付功能进行一个概述. 内容大纲: 一.常见的支付方案简介 二.第三方支付SDK 三.苹果官方支付方案 四.Web支付方案 正文: 一.常见的支付方案简介 在微信支付中 微 ...

  2. iOS开发: 向右滑动手势功能实现

    在navigationController中实现向右滑动 返回功能 系统提供的backbarbuttonitem,不用添加任何代码即可实现向右滑动后退功能,但是往往要对按钮修改样式等时,就需要自定义l ...

  3. iOS开发-清理缓存功能的实现

    移动应用在处理网络资源时,一般都会做离线缓存处理,其中以图片缓存最为典型,其中很流行的离线缓存框架为SDWebImage. 但是,离线缓存会占用手机存储空间,所以缓存清理功能基本成为资讯.购物.阅读类 ...

  4. iOS开发系统类功能划分

    0.OC语法基础 CHOCBase Object C语法学习笔记(一) Object C语法学习笔记(二) 1.UI类 自定义控件程序运行流程 setNeedsLayOut和setNeedsDispl ...

  5. iOS开发总结-搜索功能实现--使用SKTag

    TagsTableViewController.h 文件 #import <UIKit/UIKit.h> #import "personSearch.h" @inter ...

  6. iOS开发打电话的功能

    1,这种方法,拨打完电话回不到原来的应用,会停留在通讯录里,而且是直接拨打,不弹出提示 NSMutableString * phoneStr=[[NSMutableString alloc] init ...

  7. iOS开发笔记10:圆点缩放动画、强制更新、远程推送加语音提醒及UIView截屏

    1.使用CAReplicatorLayer制作等待动画 CALayer+CABasicAnimation可以制作很多简单的动画效果,之前的博客中介绍的“两个动画”,一个是利用一张渐变色图片+CABas ...

  8. iOS开发之窥探UICollectionViewController(四) --一款功能强大的自定义瀑布流

    在上一篇博客中<iOS开发之窥探UICollectionViewController(三) --使用UICollectionView自定义瀑布流>,自定义瀑布流的列数,Cell的外边距,C ...

  9. 深入理解iOS开发中的BitCode功能

    前言 做iOS开发的朋友们都知道,目前最新的Xcode7,新建项目默认就打开了bitcode设置.而且大部分开发者都被这个突如其来的bitcode功能给坑过导致项目编译失败,而这些因为bitcode而 ...

随机推荐

  1. webconfig简单加密解密

    <?xml version="1.0"?><configuration> <configSections> <section name=& ...

  2. c# 服务端

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...

  3. MVC模式:实现数据库中数据的增删改查功能

    *.数据库连接池c3p0,连接mysql数据库: *.Jquery使用,删除时跳出框,确定是否要删除: *.使用EL和JSTL,简化在jsp页面中插入的java语言 1.连接数据库 (1)导入连接数据 ...

  4. Cookie案例

    实现的功能是:在页面上点击,各种书名,跳转到另一个页面,在点解return 回到原来的页面,并且最下面出现刚才点击的书名:进行多次操作,都会出现刚刚点击的书名: 类似于:在浏览器上显示你登录的记录: ...

  5. Conditional - 编译屏蔽特性

    public class Test : MonoBehaviour { void Start() { Func(); } [System.Diagnostics.Conditional("U ...

  6. 2016年10月12日 星期三 --出埃及记 Exodus 18:23

    2016年10月12日 星期三 --出埃及记 Exodus 18:23 If you do this and God so commands, you will be able to stand th ...

  7. 2016年6月26日 星期日 --出埃及记 Exodus 14:23

    2016年6月26日 星期日 --出埃及记 Exodus 14:23 The Egyptians pursued them, and all Pharaoh's horses and chariots ...

  8. P2679 子串

    http://www.luogu.org/problem/show?pid=2679 题目描述 有两个仅包含小写英文字母的字符串 A 和 B.现在要从字符串 A 中取出 k 个互不重叠的非空子串,然后 ...

  9. uTenux——软件底层驱动组织结构介绍

    经过第一节对uTenux初步认识和第二节对uTenux\AT91SAM3S4C开发板的硬件结构的介绍,这一节我们将要学习的是uTenux\AT91SAM3S4C的软件底层驱动. 在悠龙公司的官网或者u ...

  10. 《微信开发日志》之OAuth2验证接口

    OAuth2接口说明: 企业应用中的URL链接(包括自定义菜单或者消息中的链接),可以通过OAuth2.0验证接口来获取员工的身份信息. 通过此接口获取用户身份会有一定的时间开销.对于频繁获取用户身份 ...