首页 > 代码库 > iOS添加Google语言识别功能
iOS添加Google语言识别功能
+ View Code?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 | #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 = http://www.mamicode.com/[[ 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 |
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。