这两天也调了一下ios的录音,原文链接:http://www.iphoneam.com/blog/index.php?title=using-the-iphone-to-record-audio-a-guide&more=1&c=1&tb=1&pb=1

这里ios的录音功能主要依靠AVFoundation.framework与CoreAudio.framework来实现

在工程内添加这两个framework

我这里给工程命名audio_text

在生成的audio_textViewController.h里的代码如下

[cpp] view plaincopy
  1. #import <UIKit/UIKit.h>
  2. #import <AVFoundation/AVFoundation.h>
  3. #import <CoreAudio/CoreAudioTypes.h>
  4. @interface audio_textViewController : UIViewController {
  5. IBOutlet UIButton *bthStart;
  6. IBOutlet UIButton *bthPlay;
  7. IBOutlet UITextField *freq;
  8. IBOutlet UITextField *value;
  9. IBOutlet UIActivityIndicatorView *actSpinner;
  10. BOOL toggle;
  11. //Variable setup for access in the class
  12. NSURL *recordedTmpFile;
  13. AVAudioRecorder *recorder;
  14. NSError *error;
  15. }
  16. @property (nonatomic,retain)IBOutlet UIActivityIndicatorView *actSpinner;
  17. @property (nonatomic,retain)IBOutlet UIButton *bthStart;
  18. @property (nonatomic,retain)IBOutlet UIButton *bthPlay;
  19. -(IBAction)start_button_pressed;
  20. -(IBAction)play_button_pressed;
  21. @end

audio_textViewController.m

[cpp] view plaincopy
  1. #import "audio_textViewController.h"
  2. @implementation audio_textViewController
  3. - (void)viewDidLoad {
  4. [super viewDidLoad];
  5. //Start the toggle in true mode.
  6. toggle = YES;
  7. bthPlay.hidden = YES;
  8. //Instanciate an instance of the AVAudioSession object.
  9. AVAudioSession * audioSession = [AVAudioSession sharedInstance];
  10. //Setup the audioSession for playback and record.
  11. //We could just use record and then switch it to playback leter, but
  12. //since we are going to do both lets set it up once.
  13. [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error: &error];
  14. //Activate the session
  15. [audioSession setActive:YES error: &error];
  16. }
  17. /*
  18. // The designated initializer. Override to perform setup that is required before the view is loaded.
  19. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
  20. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  21. if (self) {
  22. // Custom initialization
  23. }
  24. return self;
  25. }
  26. */
  27. /*
  28. // Implement loadView to create a view hierarchy programmatically, without using a nib.
  29. - (void)loadView {
  30. }
  31. */
  32. /*
  33. // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
  34. - (void)viewDidLoad {
  35. [super viewDidLoad];
  36. }
  37. */
  38. /*
  39. // Override to allow orientations other than the default portrait orientation.
  40. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
  41. // Return YES for supported orientations
  42. return (interfaceOrientation == UIInterfaceOrientationPortrait);
  43. }
  44. */
  45. - (IBAction)  start_button_pressed{
  46. if(toggle)
  47. {
  48. toggle = NO;
  49. [actSpinner startAnimating];
  50. [bthStart setTitle:@"停" forState: UIControlStateNormal ];
  51. bthPlay.enabled = toggle;
  52. bthPlay.hidden = !toggle;
  53. //Begin the recording session.
  54. //Error handling removed.  Please add to your own code.
  55. //Setup the dictionary object with all the recording settings that this
  56. //Recording sessoin will use
  57. //Its not clear to me which of these are required and which are the bare minimum.
  58. //This is a good resource: http://www.totodotnet.net/tag/avaudiorecorder/
  59. NSMutableDictionary* recordSetting = [[NSMutableDictionary alloc] init];
  60. [recordSetting setValue :[NSNumber numberWithInt:kAudioFormatAppleIMA4] forKey:AVFormatIDKey];
  61. [recordSetting setValue:[NSNumber numberWithFloat:[freq.text floatValue]] forKey:AVSampleRateKey];
  62. [recordSetting setValue:[NSNumber numberWithInt: [value.text intValue]] forKey:AVNumberOfChannelsKey];
  63. //Now that we have our settings we are going to instanciate an instance of our recorder instance.
  64. //Generate a temp file for use by the recording.
  65. //This sample was one I found online and seems to be a good choice for making a tmp file that
  66. //will not overwrite an existing one.
  67. //I know this is a mess of collapsed things into 1 call.  I can break it out if need be.
  68. recordedTmpFile = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent: [NSString stringWithFormat: @"%.0f.%@", [NSDate timeIntervalSinceReferenceDate] * 1000.0, @"caf"]]];
  69. NSLog(@"Using File called: %@",recordedTmpFile);
  70. //Setup the recorder to use this file and record to it.
  71. recorder = [[ AVAudioRecorder alloc] initWithURL:recordedTmpFile settings:recordSetting error:&error];
  72. //Use the recorder to start the recording.
  73. //Im not sure why we set the delegate to self yet.
  74. //Found this in antother example, but Im fuzzy on this still.
  75. [recorder setDelegate:self];
  76. //We call this to start the recording process and initialize
  77. //the subsstems so that when we actually say "record" it starts right away.
  78. [recorder prepareToRecord];
  79. //Start the actual Recording
  80. [recorder record];
  81. //There is an optional method for doing the recording for a limited time see
  82. //[recorder recordForDuration:(NSTimeInterval) 10]
  83. }
  84. else
  85. {
  86. toggle = YES;
  87. [actSpinner stopAnimating];
  88. [bthStart setTitle:@"开始录音" forState:UIControlStateNormal ];
  89. bthPlay.enabled = toggle;
  90. bthPlay.hidden = !toggle;
  91. NSLog(@"Using File called: %@",recordedTmpFile);
  92. //Stop the recorder.
  93. [recorder stop];
  94. }
  95. }
  96. - (void)didReceiveMemoryWarning {
  97. // Releases the view if it doesn't have a superview.
  98. [super didReceiveMemoryWarning];
  99. // Release any cached data, images, etc that aren't in use.
  100. }
  101. -(IBAction) play_button_pressed{
  102. //The play button was pressed...
  103. //Setup the AVAudioPlayer to play the file that we just recorded.
  104. AVAudioPlayer * avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:recordedTmpFile error:&error];
  105. [avPlayer prepareToPlay];
  106. [avPlayer play];
  107. }
  108. - (void)viewDidUnload {
  109. // Release any retained subviews of the main view.
  110. // e.g. self.myOutlet = nil;
  111. //Clean up the temp file.
  112. NSFileManager * fm = [NSFileManager defaultManager];
  113. [fm removeItemAtPath:[recordedTmpFile path] error:&error];
  114. //Call the dealloc on the remaining objects.
  115. [recorder dealloc];
  116. recorder = nil;
  117. recordedTmpFile = nil;
  118. }
  119. - (void)dealloc {
  120. [super dealloc];
  121. }
  122. @end

最后在interface builder里面绘制好界面,如

设置下按键的属性

基本就ok了,可以开始录音了。

BUG解决
但是大家要注意一个貌似是ios5.0之后引入的bug,就是当你录制音频的时候启动时间往往会比较慢,大概需要3--5秒的时间吧,这种现象尤其在播放的时候立刻切换到录制的时候非常明显。
具体的原因我也不是很清楚,感觉应该是更底层的一些bug。目前我的解决方案是这样的。
1.在音频队列的初始化方法中加入代码

OSStatus error = AudioSessionInitialize(NULL, NULL, NULL, NULL);

UInt32 category = kAudioSessionCategory_PlayAndRecord;

error = AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(category), &category);

AudioSessionAddPropertyListener(kAudioSessionProperty_AudioRouteChange, NULL, self);

UInt32 inputAvailable = 0;

UInt32 size = sizeof(inputAvailable);

AudioSessionGetProperty(kAudioSessionProperty_AudioInputAvailable, &size, &inputAvailable);

AudioSessionAddPropertyListener(kAudioSessionProperty_AudioInputAvailable, NULL, self);

AudioSessionSetActive(true);

2.在录制声音开始的时候先把播放声音stop,加入

UInt32 category = kAudioSessionCategory_PlayAndRecord;

AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(category), &category);

这样做应该会让你的录制启动速度显著加快的。

csdn转载:http://blog.csdn.net/ch_soft/article/details/7382411

转载于:https://www.cnblogs.com/Camier-myNiuer/p/3144577.html

iOS 录音功能的实现相关推荐

  1. android ios 录音功能,盘点:简单好用的录音APP有哪些?

    原标题:盘点:简单好用的录音APP有哪些? 本文为「智活范」原创作品,欢迎关注我们! 前段时间去跟一个采访,因为过程中要录音,遂找人介绍了一款录音APP来用.当时用下来觉得录音体验没问题,但就是界面太 ...

  2. ios录音文件路径_iOS中录音功能

    应用场景 在即时通讯APP中,例如微信,QQ,等都有语音发送功能,一般都要先将录音录制下来才能发送录音. 音频相关知识介绍: 1. 文件格式(不同的文件格式,可保存不同的编码格式的文件) 1.1 WA ...

  3. IOS系统通话录音功能的实现方案

    IOS系统通话录音功能的实现方案 前言 由于IOS系统的隐私性,在非越狱情况下没有通话录音功能,网上没有相关方案,所以写一个分享一下. 编写不易,如果可以,还希望来波点赞.关注,有想吐槽的或内容纠错的 ...

  4. ios html5 录音功能,HTML5 Audio 在 iOS Safari 上的有关问题

    HTML5 Audio 在 iOS Safari 上的问题 最近接触一个移动短项目,做摇一摇的功能,然后摇的时候要有声音,摇中奖的时候也有声音,问题来了,iOS 5 不能用代码去触发播放声音,其实 A ...

  5. php手机网页在线录音ios,iOS 实现录音功能

    参考资料 音频文件相关知识 文件格式 wav: 特点:音质最好的格式,对应PCM编码 适用:多媒体开发,保存音乐和音效素材 mp3: 特点:音质好,压缩比比较高,被大量软件和硬件支持 适用:适合用于比 ...

  6. ios中录音功能的实现AudioSession的使用

    这个星期我完成了一个具有基本录音和回放的功能,一开始也不知道从何入手,也查找了很多相关的资料.与此同时,我也学会了很多关于音频方面的东西,这也对后面的录音配置有一定的帮助.其中参照了<iPhon ...

  7. iOS 使用AVAudioPlayer开发录音功能

    最近要做一个类似对讲的功能,所以需要用到录音上传,然后再播放的功能. 一.音频格式分析 因为之前没研究过音频这块,所以很多音频格式都是第一次见. AAC: AAC其实是"高级音频编码(adv ...

  8. iOS使用AVCaptureSession自定义相机

    转自:http://www.2cto.com/kf/201409/335951.html 关于iOS调用摄像机来获取照片,通常我们都会调用UIImagePickerController来调用系统提供的 ...

  9. [iOS]iOS AudioSession详解 Category选择 听筒扬声器切换

    在你读这篇文章之前,如果你不嫌读英文太累,推荐阅读下苹果iOS Human Interface Guidelines中Sound这一章. 选择一个Category AVAudioSessionCate ...

最新文章

  1. 企业为什么要开通银企直联_企业为什么要把人事外包出去
  2. android 收不到短信广播,android – 短信广播接收器没有得到textmessage
  3. 2018年第九届蓝桥杯C/C++ C组国赛 —— 第二题:最大乘积
  4. 解决Entity Framework中DateTime类型字段异常
  5. MangoFix:iOS热修复另辟蹊径
  6. cmake 构建路径_新手必备:win10 系统下 VSCode+CMake+Clang+GCC 环境的搭建
  7. Magento教程 17:Magento功能导览(1) 会员功能
  8. 小学生计算机按键分布图,人教版(新版)小学信息三下第2课《常用按键掌握牢》课件.ppt...
  9. MapperException: 无法获取实体类xxxxx对应的表名! 三种解决方法,总有一款适合你。
  10. 搭建VUE环境、安装npm、node.js
  11. 一个类windows系统的效果图
  12. python如何执行代码漏洞_在漏洞利用Python代码真的很爽
  13. P2P终结者的工作原理
  14. 基于阿里云SDK实现发送短信功能
  15. Win8企业版如何升级至win10专业版
  16. Android有效解决加载大图片时内存溢出的问题
  17. 3DEXPERIENCE ENOVIA
  18. 惠普关闭 secure boot
  19. 创业要素:如何推广自己的产品
  20. 一切皆组件的Flutter,安能辨我是雄雌

热门文章

  1. 5G时代下的网络营销对移动端网站建设形成怎样的冲击?
  2. python 微信模块_Python使用itchat模块实现简单的微信控制电脑功能示例
  3. hashmap允许null键和值吗_hashMap底层源码浅析
  4. matlab 三维饼图,重新学习MATLAB——作图技法及3D可视化
  5. ARIMA模型实例讲解——网络流量预测可以使用啊
  6. ant-design圣诞彩蛋
  7. 设计模式 -- 装饰者模式
  8. CF#212 Two Semiknights Meet
  9. Atitit.png 图片不能显示 php环境下
  10. Unity3D 游戏引擎之脚本实现模型的平移与旋转(六)