分享一下iPhone的录音和播放的使用心得。iPhone的录音和播放使用到了media层的内容,media层处于cocoa层之下,用到的很大一部分都是c语言的结构。

1、引入框架。

#import <AVFoundation/AVFoundation.h>

2、创建录音项。
- (void) prepareToRecord
{
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *err = nil;
[audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
if(err){
NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
return;
}
[audioSession setActive:YES error:&err];
err = nil;
if(err){
NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
return;
}
recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
[recordSetting setValue :[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
[recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
[recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];
// Create a new dated file NSDate *now = [NSDate dateWithTimeIntervalSinceNow:0];
NSString *caldate = [now description];
recorderFilePath = [[NSString stringWithFormat:@"%@/%@.caf", DOCUMENTS_FOLDER, caldate] retain];
NSURL *url = [NSURL fileURLWithPath:recorderFilePath];
err = nil;
recorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:&err];
if(!recorder){
NSLog(@"recorder: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
UIAlertView *alert =
[[UIAlertView alloc] initWithTitle: @"Warning"
message: [err localizedDescription]
delegate: nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return;
}
//prepare to record
[recorder setDelegate:self];
[recorder prepareToRecord];
recorder.meteringEnabled = YES;
BOOL audioHWAvailable = audioSession.inputIsAvailable;
if (! audioHWAvailable) {
UIAlertView *cantRecordAlert =
[[UIAlertView alloc] initWithTitle: @"Warning"
message: @"Audio input hardware not available"
delegate: nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[cantRecordAlert show];
[cantRecordAlert release];
return; }
}
以上这个方法就是创建了录音项,其中包括录音的路径和一些音频属性,但只是准备录音还没有录,如果要录的话还要加入以下的方法:
(void)startrecorder {
[recorder record];
}
这样就在我们创建的路径下开始了录音。完成录音很简单:
(void) stopRecording{
[recorder stop];
}
这里顺便提一下录音的代理方法:
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *) aRecorder successfully:(BOOL)flag {
NSLog(@"recorder successfully");
UIAlertView *recorderSuccessful =
[[UIAlertView alloc] initWithTitle:@""
message:@"录音成功"delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[recorderSuccessful show];
[recorderSuccessful release];
}
- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)arecorder error:(NSError *)error {
btnRecorder.enabled = NO;
UIAlertView *recorderFailed =
[[UIAlertView alloc] initWithTitle:@"" message:@"发生错误"
delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[recorderFailed show];
[recorderFailed release];
}
以上两个代理方法分别指定了录音的成功或失败。

录音中有一个的录音对象有一个averagePowerForChannel和peakPowerForChannel的属性分别为声音的最高振幅和平均振幅,有了他们就可以做一个动态的振幅的录音效果。

- (void) updateAudioDisplay {
if (isStart == NO) {
currentTimeLabel.text = @"--:--";
}
else {
double currentTime = recorder.currentTime;
currentTimeLabel.text = [NSString stringWithFormat: @"d:d",
(int) currentTime/60, (int) currentTime%60];
//START:code.RecordViewController.setlevelmeters
[recorder updateMeters];
[leftLevelMeter setPower: [recorder averagePowerForChannel:0] peak: [recorder peakPowerForChannel: 0]];
if (! rightLevelMeter.hidden) {
[rightLevelMeter setPower: [recorder averagePowerForChannel:1] peak: [recorder peakPowerForChannel: 1]];
}
//END:code.RecordViewController.setlevelmeters
}
}
以上就是录音相关的内容。
下面说一下播放的方法:
void SystemSoundsDemoCompletionProc ( SystemSoundID soundID, void *clientData) {
AudioServicesDisposeSystemSoundID (soundID);
((AudioRecorderPlayerAppDelegate*)clientData).statusLabel.text = @"Stopped";
}
-(void)playAudio {
//START:code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound
// create a system sound id for the selected row SystemSoundID soundID;
OSStatus err = kAudioServicesNoError;
// special case: vibrate
//震动
//soundID = kSystemSoundID_Vibrate;
//<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.vibratesystemsound"/>
// find corresponding CAF file
//NSString *cafName = [NSString stringWithFormat: @"%@",recorderFilePath];
//<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.rowtonumberstring"/>
NSURL *url = [NSURL fileURLWithPath:recorderFilePath];
//NSString *cafPath =
//[[NSBundle mainBundle] pathForResource:cafName ofType:@"caf"];
//<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.findcafinbundle"/>
//NSURL *cafURL = [NSURL fileURLWithPath:url];
//<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.fileurlwithpath"/> err = AudioServicesCreateSystemSoundID((CFURLRef) url, &soundID);
//<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.createsystemsound"/>
//END:code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound
//START:code.SystemSoundsDemo.SystemSoundsDemoViewController.registercompletionprocandplaysound
if (err == kAudioServicesNoError) {
// set up callback for sound completion err = AudioServicesAddSystemSoundCompletion
//<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.addcompletionproc"/>(soundID,
// sound to monitor NULL,
// run loop (NULL==main) NULL,
// run loop mode (NULL==default) SystemSoundsDemoCompletionProc,
// callback function
//<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.completionprocroutine"/> self
// data to provide on callback );
//<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.addcompletionprocend"/> statusLabel.text = @"Playing";
//<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.setlabel"/> AudioServicesPlaySystemSound (soundID);
//<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.playsound"/>
}
if (err != kAudioServicesNoError) {
//<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.errorblockstart"/>
CFErrorRef error = CFErrorCreate(NULL, kCFErrorDomainOSStatus, err, NULL);
//<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.createcferror"/>
NSString *errorDesc = (NSString*) CFErrorCopyDescription (error);
//<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.copycferrordescription"/>
UIAlertView *cantPlayAlert = [[UIAlertView alloc] initWithTitle:@"Cannot Play:" message: errorDesc delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [cantPlayAlert show];
[cantPlayAlert release];
[errorDesc release];
//<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.releaseerrordescription"/>
CFRelease (error);
//<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.releaseerror"/>
}
//<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.errorblockend"/>
//END:code.SystemSoundsDemo.SystemSoundsDemoViewController.registercompletionprocandplaysound
}
通过以上的方法就应该能够实现播放,播放的时候也是可以加入振幅过程的,大家可以试试!这样一个iPhone录音机就做好了

实例编程iPhone 录音和播放(收藏)相关推荐

  1. 实例编程iPhone 录音和播放

    实例编程iPhone 录音和播放是本文要介绍的内容,最近准备做一个关于录音和播放的项目!查了一些资料,很简单的做了一个,下面我就分享一下iPhone的录音和播放的使用心得.iPhone的录音和播放使用 ...

  2. iphone 录音与播放同时 音量问题

    播放与录音同时开工: AVAudioSession *audioSession = [AVAudioSession sharedInstance]; NSError *err = nil; [audi ...

  3. iPhone的录音和播放

    最近准备做一个关于录音和播放的项目!查了一些资料,很简单的做了一个,下面我就分享一下iPhone的录音和播放的使用心得. iPhone的录音和播放使用到了media层的内容,media层处于cocoa ...

  4. Android 实时录音和回放,边录音边播放 (KTV回音效果)

    原文地址为: Android 实时录音和回放,边录音边播放 (KTV回音效果) 上一篇介绍了如何使用Mediarecorder来录音,以及播放录音.不过并没有达到我的目的,一边录音一边播放.今天就讲解 ...

  5. unity获取麦克风音量_Unity调取移动端的麦克风进行录音并播放

    本文实例为大家分享了Unity调取移动端的麦克风进行录音并播放的具体代码,供大家参考,具体内容如下 1.对MicroPhone类的理解 对麦克风的调用在Unity里主要是用到了MicroPhone这个 ...

  6. 微信小程序录音与播放录音功能实现

    微信小程序录音与播放录音功能实现,话不多说直接上代码实例: test.wxml <button bindtap='start'>开始录音</button> <button ...

  7. c语言i o编程,C实例编程:在C语言下使用I/O端

    1. 正规的方法 用来存取 i/o 埠的常式 (routine) 都放在档案 /usr/include/asm/io.h 里 (或放在核心原始码程式集的 linux/include/asm-i386/ ...

  8. Android录音并播放(mp3或amr格式)

    Android项目中媒体是很多人头疼的一个问题,不仅仅因为处理起来很麻烦,而且不同的手机差别很大(和硬件,系统都有关系),今天就总结一下Android中的录音和播放,可保存成mp3或amr格式. 小米 ...

  9. Android JNI实现录音和播放

    1.jni 部分开发,实现录音和播放 2.实现so库有效时间限制 /*** 引用和声明JNI库和函数的类*/public class RecoderJni {static {System.loadLi ...

最新文章

  1. C# Window编程随记——ClickOnce程序部署
  2. 鹅厂是如何使用 Git 的?
  3. asp.net中page对象生命周期和各事件执行顺序
  4. python学习手册视频教程-Python学习精品教程,视频书籍打包下载
  5. 超市账单管理系统设计思路
  6. layui 给table里面的添加图标_layui中的table中toolbar自定义过程
  7. 使用宝塔部署node项目_使用宝塔面板进行项目的自动部署WebHook
  8. java中匿名数组_Swagger UI:数组中的多个匿名对象
  9. php mysql 冒号_php – 使用pdo在搜索变量中使用冒号(:)进行查询
  10. SpringMVC自学日志01(回顾servlet)
  11. 导致大量kworker的原因_氨氮超标的几种原因及解决办法
  12. Maven传递依赖冲突解决(版本冲突)
  13. “百度贴吧之父”俞军:百度最大的问题是缺少竞争
  14. 项目:识别Twitter用户性别
  15. 通达oa php漏洞,通达OA前台任意用户登录漏洞
  16. PDF删除页面免费的方法有什么?PDF怎么删除页面的技巧你不能错过
  17. 百度信息流 绑定服务器,百度信息流账户怎么搭建?百度信息流账户搭建教程...
  18. 「Python编程规范」语句分隔符号
  19. Win10下安装python和pycharm
  20. python身份证系统_(二)Python GUI实战:身份证信息校验系统

热门文章

  1. 独立于计算机硬件什么意思,图形卡交叉射击是什么意思? _计算机硬件和网络_IT /计算机_信息...
  2. linux文件夹指向其他电脑,分享|Syncthing: 一个在计算机之间同步文件/文件夹的私密安全同步工具...
  3. 研究生与大学生的区别
  4. ca-bundle.crt文件,用于php发起外部https请求
  5. 智能家居与SmartConfig技术,WI-FI直连
  6. Vue实例——使用canvas封装polyline组件绘制一个五角星
  7. 前端规范css篇——样式重置,字体颜色,行间距
  8. 凭什么变成现在这个样子
  9. APE与FLAC格式对比
  10. dnf服务器喇叭涨价消息,关于近期服务器喇叭价格走低的一些吐槽