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 ...
随机推荐
- gulp折腾日记——gulp-livereload
大家好,虽然在博客园注册了很长一段时间,但我还没在博客园写过博客,这是在博客园的第一篇博客,希望能养成每周写博客的好习惯 O(∩∩)O~~) 今天要聊得是gulp的一个实时刷新的插件gulp-live ...
- C#:查询某年(1900-2100)某月的日历
using System;using System.Collections.Generic;public class Program { /********************主函数 ...
- ACM 比大小
比大小 时间限制:3000 ms | 内存限制:65535 KB 难度:2 描述 给你两个很大的数,你能不能判断出他们两个数的大小呢? 比如123456789123456789要大于-1234 ...
- wemall app商城源码Android中ViewHolder详细解释
1.ViewHolder的解释: (1).只是一个静态类,不是Android的API方法. (2).它的作用就在于减少不必要的调用findViewById,然后把对底下的控件引用存在ViewHolde ...
- KoaHub平台基于Node.js开发的Koa router路由插件代码信息详情
koa-router Router middleware for koa. Provides RESTful resource routing. koa-router Router mid ...
- 3403: [Usaco2009 Open]Cow Line 直线上的牛
3403: [Usaco2009 Open]Cow Line 直线上的牛 Time Limit: 3 Sec Memory Limit: 128 MBSubmit: 71 Solved: 62[S ...
- hdoj1072 Nightmare bfs
题意:在一个地图里逃亡,2是起点,3是终点,1是路,0是墙,逃亡者携带一个炸弹,6分钟就会炸,要在6分钟前到达4可以重制时间,问是否能逃亡,若能则输出最小值 我的思路:bfs在5步内是否存在3,存在则 ...
- Office 365开发概述及生态环境介绍(一)
原文于2017年3月13日首发于LinkedIn,请参考这个链接 离上一篇文章,很快又过去了两星期的时间.今天抓紧晚上的时间,开始了Office 365开发系列文章的第一篇,我会帮助大家回顾一下过去O ...
- JavaScript-变量的作用域面试题
块级作用域 - 在其他的语言中,任何一对花括号中的语句都属于一个块,在这之中定义的所有变量在代码块外是不可见的 - JavaScript中没有块级作用域 //这里只有函数中定义的变 ...
- windows phone 8.1开发:磁铁|Tile更新
原文出自:http://www.bcmeng.com/tile/ 上一篇给大家分享了toast通知操作的方法,这一篇文章我们就来看windows phone 8.1开发中的磁铁更新.磁铁是window ...