iOS添加Google语言识别功能

+ ?





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 = [[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

iOS添加Google语言识别功能

时间: 2024-08-08 18:10:24

iOS添加Google语言识别功能的相关文章

iOS平台添加Google Admob -2/2(Unity3D开发之八)

猴子原创,欢迎转载.转载请注明: 转载自Cocos2D开发网–Cocos2Dev.com,谢谢! 原文地址: http://www.cocos2dev.com/?p=572 在上一篇文章中主要是编写了iOS Admob的接口实现.那么现在我们要做的事就是在unity中调用iOS Admob并展示. 一.实现Unity中对外接口,内部负责调用iOS Admob接口.LHiOSAdmob.cs using UnityEngine; using System.Collections; using Sy

iOS平台添加Google Admob -1/2(Unity3D开发之七)

猴子原创,欢迎转载.转载请注明: 转载自Cocos2D开发网–Cocos2Dev.com,谢谢! 原文地址: http://www.cocos2dev.com/?p=567 Unity调用iOS还是非常简单的,晚上空闲时间写了unity在IOS平台加载Google Admob.需要的朋友可以看下. 一.首先编写Admob的iOS的代码.请去https://apps.admob.com下载iOS Admob SDK, 并注册app id.如果这一步不熟悉,请自行Google,网上应该很多. 1.I

iOS略记小功能

在我们进行开发工程的时候,有些小的功能能提高用户的体验,但是这些小的功能记忆起来比较麻烦,很容易忘记,在这里我整理一下自己使用过的小功能罗列出来. 一.项目在设备上得图标及名称的设定 1).图标:在项目中把你想要用得项目图标添加到项目中并且改名为icon(必须为png格式). 2).名称:在项目的Info.plist文件中有Key为Bundle display name一行的Value值改为自己所需要的名称即可 二.在程序启动还未进入程序起始界面前展示的Image 在工程选项中的General中

添加顶踩功能

phpcms如何添加顶踩功能步骤: 1.在后台模型增加两个字段,一个goodpost,一个badpost;这个步骤简单,按后台新增加字段下一步就行了. 2.在模块/phpcms/modules/content/增加扩展函数newindex.php,代码如下: <?php defined('IN_PHPCMS') or exit('No permission resources.'); class newindex{ function __construct(){ $this->db=pc_ba

使用EasyUI实现添加和删除功能

        增删该查是任何一个项目都少不了的功能操作,这篇博文主要简介一下如何使用EasyUI实现添加和删除功能.         首先,导入EasyUI的js代码: <link href="~/EasyuiSource/themes/default/easyui.css" rel="stylesheet" /> <link href="~/EasyuiSource/themes/icon.css" rel="st

使用prismjs为网站添加代码高亮功能

prismjs 是一款轻量.可扩展的代码语法高亮库,使用现代化的 Web 标准构建,使用 Prismjs 可以快速为网站添加代码高亮功能,支持超过113中编程语言,还支持多种插件,是简洁.高效的代码高亮解决方案.科技爱好者博客就是使用了Prism.js 实现漂亮的代码语法高亮功能,本文教你如何在wordpress上快速使用Prismjs实现代码高亮. 一.下载JS和CSS文件并上传到网站根目录. 在Prismjs网站下载页面下载需要的JS和CSS文件,下载页面: http://prismjs.c

用汇编语言给XP记事本添加“自动保存”功能 good

[文章标题]: 用汇编语言给XP记事本添加“自动保存”功能 [文章作者]: newjueqi [作者邮箱]:[email protected] [作者QQ]:190678908 [使用工具]: OD, LordPE,eXeScope[操作平台]: XP-SP2[作者声明]: 本人平时一般的文字处理都是用记事本(用Word好像大材小用了),电脑自从拿去大修后有时候会莫名其妙的重启,弄得经常重写(本人常常忘记保存^-^),于是想给记事本增加类似于Word的自动保存功能,以图个方便.失误之处敬请诸位大

不能因为为了添加一个新功能,影响到旧的功能

涉及到后台的, 一般都是要跟数据库打交道的大型数据量的处理问题.以类 client - server 为基础的架构, 或者变形后的架构. 客户端处理用户的输入和数据, 然后大量的客户端(多个客户端的多种数据) 反馈到服务端统一处理和协调, 然后服务端对客户端发出相应的指令.其中 后台程序 代表的就是服务端的程序. 包含以下几点:1. 网络通信,  要跟远程的client打交道,只能用网络2. 并发 和 并行处理.0.. 多个客户端可能在同一时间同时需要处理同一个类型的数据, 谁先谁后,谁的有效谁

IOS开发之支付功能概述

前言:本随笔将对IOS开发的支付功能进行一个概述. 内容大纲: 一.常见的支付方案简介 二.第三方支付SDK 三.苹果官方支付方案 四.Web支付方案 正文: 一.常见的支付方案简介 在微信支付中 微信支付的网址是: https://pay.weixin.qq.com/wiki/doc/api/index.html 进去之后,我们可以看到网页,但我接下来主要讲的是app支付 app支付的过程:商业app通过集成微信SDK,用户解析后跳转到微信内软件支付的过程. 点进去app支付: 我们可以看到A