在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. MATLAB(5)——生成归一化直方图

    作者:桂. 时间:2017-03-10  22:13:36 链接:http://www.cnblogs.com/xingshansi/p/6533579.html 声明:欢迎转载,不过记得注明出处哦~ ...

  2. 九度OJ题目1080:进制转换(java)使用BigInteger进行进制转换

    题目描述: 将M进制的数X转换为N进制的数输出. 输入: 输入的第一行包括两个整数:M和N(2<=M,N<=36). 下面的一行输入一个数X,X是M进制的数,现在要求你将M进制的数X转换成 ...

  3. Markdown语法讲解及MWeb使用教程

    写了一个月的博客,忽然感觉Markdown编辑器比较好用,于是就下载了一个本地的Markdown编辑软件学习了一下,刚好软件里自带了一篇英文的指示文档,顺便翻译了一下,通过这个过程也大致熟悉了Mark ...

  4. 分享一些自己写的前端库,并骗骗 star(库都是在实际项目中大量运用过的)

    最近一两年在一些项目上,通过实际需求出发,编写了一些库在项目中使用,现在将这些项目都稍微整理了一下开源了出来,也许也有刚好能够你也用得上的,顺便也骗一下star.均在项目的README中加了相关的说明 ...

  5. Android之XListView下拉刷新,更新网络美女图

    一.简介:   下拉刷新是一种特定的手动刷新交互,和其他的同类操作不同的地方在于它采用了更加直觉的下拉操作,所以它的交互足够清晰明显. 下拉刷新主要用在类似ListView这样的控件,设计下拉刷新有三 ...

  6. 使用Func<>和Action简化委托

    /// <summary> /// 入口 /// </summary> public void Run() { TestDelegate t = test; t(); Acti ...

  7. SpringMVC REST 风格请求介绍及简单实践

    简介 REST 即 Representational State Transfer.(资源)表现层状态转化.是目前最流行的一种互联网软件架构.它结构清晰.符合标准.易于理解.扩展方便,所以正得到越来越 ...

  8. python3.6 简单爬虫

    # coding='UTF-8' from bs4 import BeautifulSoup # 引入beautifulsoup 解析html事半功倍 import re import urllib ...

  9. iOS开发之自定义UITableView的cell

    系统默认的UITableViewCell的每行都有横线(分隔符),就算没有数据也是如此,有时候我们想只在有数据的地方有下划线,可以去除下划线,然后在awarkFromNid方法中使用addsubvie ...

  10. JS和Flash(AS)相互调用

    <!DOCTYPE html> <html> <head> <title>swf</title> <meta charset=&quo ...