• iOS开发之语音功能实现


     

    - (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];

     }

    提高技能如同提升自信心。
  • 相关阅读:
    shell脚本
    centos7.6通过单用户模式重置密码
    小端
    malloc函数
    float和double数据EEPROM存储
    分享一个的c++写的,模仿awk的框架类CAwkDoc
    简单自测项目pom配置,log4j配置
    idea 启动项目,maven打包错误整理
    docker,docker-compose常用命令及部署
    jrebel启动项目报Incompatible magic value 0 in class file错误
  • 原文地址:https://www.cnblogs.com/chims-liu-touch/p/5388149.html
Copyright © 2020-2023  润新知