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 ...
随机推荐
- Asp.Net 常用工具类之Office-文档操作(6)
文档一直是老大难问题,君不知,代码用时方恨少!有一套成熟的文件帮助类能很大程度上减少寻找各种资料的时间. 记得以前做一个业务,需要导出协议,一份可编辑,一份不可编辑.那么Word和PDF是最好的选择, ...
- Hibernate打印SQL及附加参数
今天在项目运行过程中,一直报一个org.hibernate.exception.GenericJDBCException: could not insert 异常,Root Cause是IBM DB ...
- warning: in-class initialization of non-static data member is a C++11 extension [-Wc++11-extensions]
struct test{int a=1111111; }test; vincentdeMacBook-Air:datasturte vincent$ g++ struct.cpp -o structp ...
- 页面异步发送json数据封装controller方法形参 pojo中,使用@requestBody和不使用它页面的异步方式不同之处
方式一: 使用@requestBody 方式二 : 直接封装到pojo的方式
- 模拟一个shuffle
之所以会想到写这么一个shuffle的例子,是因为一个需求:我需要把一个有序数组中的数据随机的打散.java代码如下, public void shuffle() { int[] arr = {1,2 ...
- Java虚拟机工作原理
Java虚拟机工作原理 首先我想从宏观上介绍一下Java虚拟机的工作原理.从最初的我们编写的Java源文件(.java文件)是如何一步步执行的,如下图所示,首先Java源文件经过前端编译器(javac ...
- Linux云自动化运维第四课
Linux云自动化运维第四课 一.vim 1.vim光标移动 1)在命令模式下 :数字 ###移动到指定的行 G ###文件最后一行 gg ###文件第一行 2)在插入模式下 i ###光标所 ...
- 设计模式的征途—1.单例(Singleton)模式
单例模式属于创建型模式的一种,创建型模式是一类最常用的设计模式,在软件开发中应用非常广泛.创建型模式将对象的创建和使用分离,在使用对象时无需关心对象的创建细节,从而降低系统的耦合度,让设计方案更易于修 ...
- django出现__init__() got an unexpected keyword argument 'mimetype‘ 问题解决
这种问题好多新手按照djangobook学习的时候应该都遇到过,是因为这是老的django的写法,新的django已经升级改变了很多东西. 处理方法如下: I think you are not us ...
- signedCookies
var express = require('../') , request = require('supertest') , cookieParser = require('cookie-parse ...