iOS添加Google语言识别功能

#import <UIKit/UIKit.h>

#import <AVFoundation/AVFoundation.h>

#import <QuartzCore/QuartzCore.h>

 

@interface RootViewController : UIViewController<AVAudioRecorderDelegate,UIAlertViewDelegate>

{

    AVAudioRecorder *recoder;

    NSURLConnection *urlConnection;

    NSMutableData *receiveData;

    NSTimer *timer;

    NSTimeInterval bInterval;

    

    UIAlertView *wAlertView;

}

 

@end

 

//

//  RootViewController.m

//  asr

//

//  Created by cat on 14-3-20.

//  Copyright (c) 2014年 cat. All rights reserved.

//

 

#import "RootViewController.h"

 

@interfaceRootViewController ()

 

 

@end

 

@implementation RootViewController

 

- (void)viewDidLoad

{

    [superviewDidLoad];

// Do any additional setup after loading the view.

}

 

- (void)didReceiveMemoryWarning

{

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

- (void)dealloc

{

    if(recoder)

    {

        [recoder stop];

        [recoder release];

    }

    [urlConnectionrelease];

    

    [super dealloc];

}

 

- (void)loadView

{

    [super loadView];

    

    NSString *str[] = {@"Record", @"Play"};

    float y = 64.0f;

    for(int i = 0;i < sizeof(str) / sizeof(str[0]); i++)

    {

        UIButton *button = [UIButtonbuttonWithType:UIButtonTypeRoundedRect];

        button.frame = CGRectMake(160.0f - 40.0f, y, 80.0f, 80.0f);

        button.tag = 100 + i;

        button.layer.masksToBounds = YES;

        button.layer.cornerRadius = 40.0f;

        button.layer.borderColor = [[UIColor redColor] CGColor];

        [button setTitle:str[i] forState:UIControlStateNormal];

        if(i != 0)

            [button addTarget:selfaction:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];

        [self.view addSubview:button];

        

        if(i == 0)

        {

            UILongPressGestureRecognizer *gestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];

            [button addGestureRecognizer:gestureRecognizer];

            [gestureRecognizer release];

        }

        

        y += button.bounds.size.width + 40.0f;

    }

    

    receiveData = [[NSMutableData alloc] init];

    [[AVAudioSessionsharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecorderror: nil];

}

 

- (void)longPress:(UILongPressGestureRecognizer *)gestureRecognizer

{

    if([gestureRecognizer state] == UIGestureRecognizerStateBegan)

    {

        [self record];

    }

    elseif([gestureRecognizer state] == UIGestureRecognizerStateEnded)

    {

        [selfparseStringFromWav];

    }

}

 

- (void)parseStringFromWav

{

    wAlertView = [[UIAlertViewalloc] initWithTitle:@"Please Wait"message:nildelegate:selfcancelButtonTitle:nilotherButtonTitles:nil];

    [wAlertViewshow];

    

    UIActivityIndicatorView *aiv = [[UIActivityIndicatorViewalloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];

    aiv.center = CGPointMake(wAlertView.bounds.size.width / 2.0f, wAlertView.bounds.size.height - 40.0f);

    [aiv startAnimating];

    

    [wAlertView addSubview:aiv];

    [aiv release];

    

    [wAlertViewrelease];

    

    if(recoder)

    {

        [recoder stop];

    }

    if(timer)

    {

        [timer invalidate];

        timer = nil;

    }

    

    NSURL *url = [NSURLURLWithString:@"http://www.google.com/speech-api/v1/recognize?xjerr=1&client=chromium&lang=zh"];

    

    //Create the request

    NSMutableURLRequest *request = [[[NSMutableURLRequestalloc] init] autorelease];

    

    //头部设置

    NSDictionary *headField = [NSDictionarydictionaryWithObjectsAndKeys:@"audio/L16; rate=16000",@"Content-Type", nil];

    [request setAllHTTPHeaderFields:headField];

    

    //要post的网址

    [request setURL:url];

    [request setHTTPMethod:@"POST"];

    [request setHTTPBody:[NSDatadataWithContentsOfFile:[selfrecordTmpPath]]];

    

    if(urlConnection)

    {

        [urlConnectioncancel];

        [urlConnectionrelease];

        urlConnection = nil;

    }

    urlConnection = [[NSURLConnectionalloc] initWithRequest:request delegate:selfstartImmediately:YES];

    [urlConnectionstart];

}

 

- (void)buttonPressed:(UIButton *)sender

{

    if(sender.tag == 101)

    {

        NSError *error;

        NSURL *url = [NSURL fileURLWithPath:[self recordTmpPath]];

        AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];

        if(!audioPlayer)

        {

            NSLog(@">>>>>>>>>>audioplayer cant not init");

            return;

        }

        if(![audioPlayer prepareToPlay])

        {

            NSLog(@">>>>>>>>>>not prepareToPlay");

            return;

        }

        if(![audioPlayer play])

        {

            NSLog(@">>>>>>>>>>not play");

        }

    }

}

 

- (NSString *)recordTmpPath

{

    return [NSTemporaryDirectory() stringByAppendingFormat:@"voice.wav"];

}

 

- (BOOL)record

{

    NSError *error;

    

    NSMutableDictionary *settings = [NSMutableDictionarydictionary];

    

    [settings setValue:[NSNumbernumberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];

    [settings setValue:[NSNumbernumberWithFloat:16000] forKey:AVSampleRateKey];

    [settings setValue:[NSNumbernumberWithInt:1] forKey:AVNumberOfChannelsKey];

    [settings setValue:[NSNumbernumberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];

    

    NSLog(@">>>>>>>>>>path %@", [selfrecordTmpPath]);

    

    NSURL *url = [NSURL fileURLWithPath:[self recordTmpPath]];

    if(recoder)

    {

        [recoder release];

        recoder = nil;

    }

    recoder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];

    if(!recoder)

    {

        NSLog(@">>>>>>Error %@", [error localizedDescription]);

        return NO;

    }

    

    recoder.delegate = self;

    

    if(![recoderprepareToRecord])

    {

        [selfshowAlert:@"Error while preparing recording..."];

        return NO;

    }

    

    if(![recoder record])

    {

        [selfshowAlert:@"Error while attempting to record audio..."];

        return NO;

    }

    

    if(timer)

    {

        [timer invalidate];

        timer = nil;

    }

    

    bInterval = [[NSDatedate] timeIntervalSince1970];

    timer = [NSTimerscheduledTimerWithTimeInterval:1.0ftarget:selfselector:@selector(update) userInfo:nilrepeats:YES];

    

    returnYES;

}

 

- (void)update

{

    int sec = [[NSDatedate] timeIntervalSince1970] - bInterval;

    self.title = [NSString stringWithFormat:@"%ds", sec];

}

 

- (void)viewWillDisappear:(BOOL)animated

{

    if(timer)

    {

        [timer invalidate];

        timer = nil;

    }

}

 

- (void)updateMeters

{

    [recoderupdateMeters];

    

    float peakPowerForChannel = pow(10, 0.05 * [recoder peakPowerForChannel:0]);

    float averagePowerForChannel = pow(10, 0.05*[recoder averagePowerForChannel:0]);

    NSLog(@"Average input: %f Peak input: %f", peakPowerForChannel,averagePowerForChannel);

}

 

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

{

    NSLog(@">>>>>>>>>>audioRecorderDidFinishRecording");

}

 

/* if an error occurs while encoding it will be reported to the delegate. */

- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error

{

    NSLog(@">>>>>>>>>>audioRecorderEncodeErrorDidOccur %@", [error localizedDescription]);

}

 

- (void)showAlert:(NSString *)aMessage

{

    UIAlertView *alertView = [[UIAlertViewalloc] initWithTitle:@"提示"message:aMessage delegate:nilcancelButtonTitle:@"确定"otherButtonTitles:nil];

    [alertView show];

    [alertView release];

}

 

 

#pragma mark -

#pragma mark NSURLConnection delegate Methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

    [receiveDatasetLength:0];

}

 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    if(data)

        [receiveData appendData:data];

}

 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    NSLog(@">>>>>>>>>>connectionDidFinishLoading");

    [wAlertViewdismissWithClickedButtonIndex:0animated:NO];

    

    NSString *result = [[[NSStringalloc] initWithData:receiveDataencoding:NSUTF8StringEncoding] autorelease];

    [self showAlert:result];

}

 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{

    NSLog(@">>>>>>>>>>didFailWithError %@",[error localizedDescription]);

    [wAlertViewdismissWithClickedButtonIndex:0animated:YES];

}

 

@end
 
原文地址:https://www.cnblogs.com/gcat/p/3747642.html