在IOS中,在做语音识别中,需要对语音进行抓取。

#import "GetAudioViewController.h"

#import <AVFoundation/AVFoundation.h>

#import <UIKit/UIKit.h>

#import <ImageIO/ImageIO.h>

#import <MobileCoreServices/MobileCoreServices.h>

#import <QuartzCore/QuartzCore.h>

@interface GetAudioViewController ()

{

AVAudioPlayer *_player;

AVAudioRecorder *_audiorecord;

NSTimer* _timerForPitch;

CAShapeLayer *_shapeLayer;

CADisplayLink* _displayLink;

__weak IBOutlet UIProgressView *_audioPower;

__weak IBOutlet UIButton *_record;

__weak IBOutlet UIButton *_pause;

__weak IBOutlet UIButton *_resume;

__weak IBOutlet UIButton *_stop;

__weak IBOutlet UIView *_viewForWave;

float Pitch;

NSInteger _recordEncoding;

CFTimeInterval _firstTimestamp;

NSInteger _loopCount;

}

@end

@implementation GetAudioViewController

- (void)viewDidLoad {

[super viewDidLoad];

}

-(void)cratePath:(NSString*)path

{

NSFileManager* filemanager = [NSFileManager defaultManager];

if(![filemanager fileExistsAtPath:path])

[filemanager createDirectoryAtPath:path

withIntermediateDirectories:YES

attributes:nil

error:nil];

}

- (UIBezierPath *)pathAtInterval:(NSTimeInterval) interval

{

UIBezierPath *path = [UIBezierPath bezierPath];

[path moveToPoint:CGPointMake(0, _viewForWave.bounds.size.height / 2.0)];

CGFloat fractionOfSecond = interval - floor(interval);

CGFloat yOffset = _viewForWave.bounds.size.height * sin(fractionOfSecond * M_PI * Pitch*8);

[path addCurveToPoint:CGPointMake(_viewForWave.bounds.size.width, _viewForWave.bounds.size.height / 2.0)

controlPoint1:CGPointMake(_viewForWave.bounds.size.width / 2.0, _viewForWave.bounds.size.height / 2.0 - yOffset)

controlPoint2:CGPointMake(_viewForWave.bounds.size.width / 2.0, _viewForWave.bounds.size.height / 2.0 + yOffset)];

return path;

}

- (void)addShapeLayer

{

_shapeLayer = [CAShapeLayer layer];

_shapeLayer.path = [[self pathAtInterval:2.0] CGPath];

_shapeLayer.fillColor = [[UIColor redColor] CGColor];

_shapeLayer.lineWidth = 1.0;

_shapeLayer.strokeColor = [[UIColor whiteColor] CGColor];

[_viewForWave.layer addSublayer:_shapeLayer];

}

- (void)handleDisplayLink:(CADisplayLink *)displayLink

{

if (!_firstTimestamp)

_firstTimestamp = displayLink.timestamp;

_loopCount++;

NSTimeInterval elapsed = (displayLink.timestamp - _firstTimestamp);

_shapeLayer.path = [[self pathAtInterval:elapsed] CGPath];

}

- (void)startDisplayLink

{

_displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(handleDisplayLink:)];

[_displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

}

- (IBAction)recordClick:(id)sender {

_viewForWave.hidden = NO;

[self addShapeLayer];

[self startDisplayLink];

NSLog(@"startRecording");

_audiorecord = nil;

AVAudioSession *audioSession = [AVAudioSession sharedInstance];

[audioSession setCategory:AVAudioSessionCategoryRecord error:nil];

NSMutableDictionary *recordSettings = [[NSMutableDictionary alloc] initWithCapacity:10];

if(_recordEncoding == 6)

{

[recordSettings setObject:[NSNumber numberWithInt: kAudioFormatLinearPCM] forKey: AVFormatIDKey];

[recordSettings setObject:[NSNumber numberWithFloat:44100.0] forKey: AVSampleRateKey];

[recordSettings setObject:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];

[recordSettings setObject:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];

[recordSettings setObject:[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];

[recordSettings setObject:[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];

}

else

{

NSNumber *formatObject;

switch (_recordEncoding) {

case 1:

formatObject = [NSNumber numberWithInt: kAudioFormatMPEG4AAC];

break;

case 2:

formatObject = [NSNumber numberWithInt: kAudioFormatAppleLossless];

break;

case 3:

formatObject = [NSNumber numberWithInt: kAudioFormatAppleIMA4];

break;

case 4:

formatObject = [NSNumber numberWithInt: kAudioFormatiLBC];

break;

case 5:

formatObject = [NSNumber numberWithInt: kAudioFormatULaw];

break;

default:

formatObject = [NSNumber numberWithInt: kAudioFormatAppleIMA4];

}

[recordSettings setObject:formatObject forKey: AVFormatIDKey];

[recordSettings setObject:[NSNumber numberWithFloat:44100.0] forKey: AVSampleRateKey];

[recordSettings setObject:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];

[recordSettings setObject:[NSNumber numberWithInt:12800] forKey:AVEncoderBitRateKey];

[recordSettings setObject:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];

[recordSettings setObject:[NSNumber numberWithInt: AVAudioQualityHigh] forKey: AVEncoderAudioQualityKey];

}

NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *docsDir = [dirPaths objectAtIndex:0];

NSString *soundFilePath = [docsDir

stringByAppendingPathComponent:@"recordTest.caf"];

NSURL *url = [NSURL fileURLWithPath:soundFilePath];

NSError *error = nil;

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

_audiorecord.meteringEnabled = YES;

if ([_audiorecord prepareToRecord] == YES){

_audiorecord.meteringEnabled = YES;

[_audiorecord record];

_timerForPitch =[NSTimer scheduledTimerWithTimeInterval: 0.01 target: self selector: @selector(levelTimerCallback:) userInfo: nil repeats: YES];

}else {

//int errorCode = CFSwapInt32HostToBig ([error code]);

//NSLog(@"Error: %@ [%4.4s])" , [error localizedDescription], (char*)&errorCode);

}

}

- (void)levelTimerCallback:(NSTimer *)timer {

[_audiorecord updateMeters];

//    float linear = pow (10, [_audiorecord peakPowerForChannel:0] / 20);

float linear1 = pow (10, [_audiorecord averagePowerForChannel:0] / 20);

if (linear1>0.03) {

Pitch = linear1+.20;//pow (10, [audioRecorder averagePowerForChannel:0] / 20);//[audioRecorder peakPowerForChannel:0];

}

else {

Pitch = 0.0;

}

//    //Pitch =linear1;

//    NSLog(@"Pitch==%f",Pitch);

//    _customRangeBar.value = Pitch;//linear1+.30;

[_audioPower setProgress:Pitch];

//    float minutes = floor(_audiorecord.currentTime/60);

//    float seconds = _audiorecord.currentTime - (minutes * 60);

//    NSString *time = [NSString stringWithFormat:@"%0.0f.%0.0f",minutes, seconds];

//    [self.statusLabel setText:[NSString stringWithFormat:@"%@ sec", time]];

//    NSLog(@"recording");

}

- (IBAction)pauseClick:(id)sender {

NSLog(@"stopRecording");

// kSeconds = 0.0;

_viewForWave.hidden = YES;

[_audiorecord stop];

[self stopDisplayLink];

_shapeLayer.path = [[self pathAtInterval:0] CGPath];

[_timerForPitch invalidate];

_timerForPitch = nil;

}

- (void)stopDisplayLink

{

[_displayLink invalidate];

_displayLink = nil;

}

- (IBAction)resumeClick:(id)sender {

AVAudioSession *audioSession = [AVAudioSession sharedInstance];

[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];

NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *docsDir = [dirPaths objectAtIndex:0];

NSString *soundFilePath = [docsDir stringByAppendingPathComponent:@"recordTest.caf"];

NSURL *url = [NSURL fileURLWithPath:soundFilePath];

NSError *error;

_player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];

_player.numberOfLoops = 0;

[_player play];

}

- (IBAction)stopClick:(id)sender {

[_player stop];

}

- (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

}

@end

代码全部在这里了。

IOS语音录取的更多相关文章

  1. iOS语音

    <span style="white-space:pre">    </span>语音技术近来可是出遍了风头,从iphone4s的siri,到微信的语音聊天 ...

  2. IOS语音集成

    1.注册讯飞账号,申请APPID(注意选择IOS平台) 2.加载所需要的类库 3.导入所需要的类库文件头 4.调用申请的APPID以及所需函数,完成语音合成(需要参考官方给出的SDK文件)   详细步 ...

  3. iOS - 语音云通讯

    iOS SDK 2.0 语音及图片消息详解本文档将详细介绍融云的语音及图片消息接口功能及使用说明.阅读本文前,我们假设您已经阅读了融云 iOS 开发指南,并掌握融云 SDK 的基本用法. 语音消息用来 ...

  4. iOS语音播报文字

    记得大学的时候学微软Window Phone时,有语音识别类似苹果的嘿,Siri.今天无聊百度搜了一下,搜到苹果语音播报文字.自己试了下还挺好玩. 1.引入框架#import <AVFounda ...

  5. iOS 语音朗读

    //判断版本大于7.0    if ([[[UIDevice currentDevice] systemVersion] integerValue] >= 7.0) {        NSStr ...

  6. ios语音输入崩溃

    游戏中任何可以输入的地方,只要调用语音输入,必然会导致app崩溃,解决方法如下: ok, so essentially the gist of it is that siri wants gl con ...

  7. iOS语音播放之切换听筒和扬声器的方法解决方案

    关于流媒体播放的相关知识可以加本人QQ:564702640 一起来讨论 [[UIDevice currentDevice] setProximityMonitoringEnabled:YES]; // ...

  8. iOS语音通话(语音对讲)

    中间参考了别人的Demo,下载地址不记得了. 因为项目需要做一个语音对讲功能,其实说白了就是类似QQ的语音通话,但是资料少之又少,研究了好久,才跟同事弄出一个粗略的版本.我记性不好,所以来记录一下,也 ...

  9. 使用Olami SDK 语音控制一个支持HomeKit的智能家居的iOS程序

    前言 HomeKit是苹果发布的智能家居平台.通过HomeKit组件,用户可以通过iphone.iPad和ipod Touch来控制智能灯泡,风扇.空调等支持HomeKit的智能家居,尤其是可以通过S ...

随机推荐

  1. maven新建的项目,不自动引入依赖包

    1.检查repository的目录是不是纯英文. 2.重新下载一次repository.   如果解决了问题,那么原因就是前面在加载repository的时候,因为断网导致了下载的包有误,无法被ecl ...

  2. 模态Model视图Push下一个视图(混合跳转)

    来自: http://www.cnblogs.com/dingding3w/p/6222626.html 如果没有UINavigationController导航栏页面之间切换是不能实现Push操作的 ...

  3. ST HW3

    7. Use the following method printPrimes() for questions a-f below. /******************************** ...

  4. 个人C++学习路线

    这段时间学习<<C++ primer >> 第四版,一边学一遍考虑,要怎么样往深处学习.查了网上的学习路线,知乎大神的问题回答,整理了一下思路,如下吧: <<C++ ...

  5. Windows下GIT安装与使用(上传远程端)

    Windows下GIT安装与使用(上传远程服务器) 1.  登陆http://msysgit.github.io/并下载Git 2.  打开下载的exe文件,一路默认(路径可以去修改).有可能电脑需要 ...

  6. aiohttp之添加静态资源路径

    所谓静态资源,是指图片.js.css等文件.官方的说明在这里. 以一个小项目来说明,下面是项目的目录结构: . ├── static │ ├── css │ │ ├── base.css │ │ ├─ ...

  7. (8)集合之List,ArrayList,LinkedList

    集合的体系结构 Collection 单列集合的接口 |----List 如果实现了List接口的集合类,具备的特点是有序,可重复 |----Set 如果实现了Set接口的集合类,集合特点无序不可重复 ...

  8. Delphi的Hint介绍以及用其重写气泡提示以达到好看的效果

    Delphi中使用提示是如此简单,只需将欲使用Hint的控件作如下设置: ShowHint := True; Hint := ‘提示信息’; 不必写一行代码,相当方便. 但有时我们又想自己定制提示的效 ...

  9. C++标准库之vector(各函数及其使用全)

    原创作品,转载请注明出处:http://www.cnblogs.com/shrimp-can/p/5280566.html iterator类型: iterator:到value_type的访问,va ...

  10. 新手向:Java基础知识

    Java 接口 接口(英文:Interface),在JAVA编程语言中是一个抽象类型,是抽象方法的集合,接口通常以interface来声明.一个类通过继承接口的方式,从而来继承接口的抽象方法. 接口并 ...