IOS语音录取
在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语音录取的更多相关文章
- iOS语音
<span style="white-space:pre"> </span>语音技术近来可是出遍了风头,从iphone4s的siri,到微信的语音聊天 ...
- IOS语音集成
1.注册讯飞账号,申请APPID(注意选择IOS平台) 2.加载所需要的类库 3.导入所需要的类库文件头 4.调用申请的APPID以及所需函数,完成语音合成(需要参考官方给出的SDK文件) 详细步 ...
- iOS - 语音云通讯
iOS SDK 2.0 语音及图片消息详解本文档将详细介绍融云的语音及图片消息接口功能及使用说明.阅读本文前,我们假设您已经阅读了融云 iOS 开发指南,并掌握融云 SDK 的基本用法. 语音消息用来 ...
- iOS语音播报文字
记得大学的时候学微软Window Phone时,有语音识别类似苹果的嘿,Siri.今天无聊百度搜了一下,搜到苹果语音播报文字.自己试了下还挺好玩. 1.引入框架#import <AVFounda ...
- iOS 语音朗读
//判断版本大于7.0 if ([[[UIDevice currentDevice] systemVersion] integerValue] >= 7.0) { NSStr ...
- ios语音输入崩溃
游戏中任何可以输入的地方,只要调用语音输入,必然会导致app崩溃,解决方法如下: ok, so essentially the gist of it is that siri wants gl con ...
- iOS语音播放之切换听筒和扬声器的方法解决方案
关于流媒体播放的相关知识可以加本人QQ:564702640 一起来讨论 [[UIDevice currentDevice] setProximityMonitoringEnabled:YES]; // ...
- iOS语音通话(语音对讲)
中间参考了别人的Demo,下载地址不记得了. 因为项目需要做一个语音对讲功能,其实说白了就是类似QQ的语音通话,但是资料少之又少,研究了好久,才跟同事弄出一个粗略的版本.我记性不好,所以来记录一下,也 ...
- 使用Olami SDK 语音控制一个支持HomeKit的智能家居的iOS程序
前言 HomeKit是苹果发布的智能家居平台.通过HomeKit组件,用户可以通过iphone.iPad和ipod Touch来控制智能灯泡,风扇.空调等支持HomeKit的智能家居,尤其是可以通过S ...
随机推荐
- Intelligent idea高效实用总结
一直使用eclipse,最近才转到idea IDE上面来,的确从效率等多个角度,idea都要优于eclipse.由于刚实用idea,不是很熟练,将常用的技巧总结集锦一下,方便以后查看,慢慢积累吧 一. ...
- C#基础笔记---浅谈XML读取以及简单的ORM实现
背景: 在开发ASP.NETMVC4 项目中,虽然web.config配置满足了大部分需求,不过对于某些特定业务,我们有时候需要添加新的配置文件来记录配置信息,那么XML文件配置无疑是我们选择的一个方 ...
- 【转】请求处理机制其二:Django中间件的解析
Middleware 开始工作了 get_response 做的第一件事就是遍历处理器的 _request_middleware 实例变量并调用其中的每一个方法,传入 HttpRequest 的实例作 ...
- Java基础之路(四)--流程控制语句
本次我们来聊一聊Java当中的循环语句. 循环语句分三种:1.for2.while3.do--while. 三种循环语句的任务是不同的,方法也是不同的.当然他们各自的流程图也是不一样的. 3.1 wh ...
- 文件上传组件FileUpload 以及邮箱搭建JavaMail
文件上传与下载 1.1 文件上传 案例: 注册表单/保存商品等相关模块! --à 注册选择头像 / 商品图片 (数据库:存储图片路径 / 图片保存到服务器中指定的目录) 文件上传,要点: 前台: 1 ...
- extern “ C”的含义
见博客:http://www.cnblogs.com/xulei/archive/2006/11/12/558139.html
- iOS开发之类扩展
在以往写代码时,我们经常是把声明写在.h文件中,把实现写在.m文件中,但是在实际开发中,如果把声明写在.h文件中会暴露程序很多属性(成员变量.成员变量的get和set方法),为了安全考虑,引入了类扩展 ...
- Linux下Scala(2.12.1)安装
一.文件准备 1.1 文件名称 scala-2.12.1.tgz 1.2 下载地址 http://www.scala-lang.org/download/2.12.1.html 二.工具准备 2.1 ...
- MySQL自动化审核平台部署说明
背景: 关于MySQL的审核的重要性就不说明了,本文的自动化审核是通过Inception和SQLAdvisor实现的,具体的使用可以看它们各自的说明文档.这里大致介绍下如何部署和使用它们,其实该文章也 ...
- tortoiseGit保存用户名和密码
简介:tortoiseGit(乌龟git)图形化了git,我们用起来很方便,但是我们拉取私有项目的时候,每次都要输入用户名和密码很麻烦,这里向大家介绍怎么避免多少输入 试验环境:window10,安装 ...