最近准备做一个关于录音和播放的项目!查了一些资料,很简单的做了一个,下面我就分享一下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 录音和播放(收藏)

    分享一下iPhone的录音和播放的使用心得.iPhone的录音和播放使用到了media层的内容,media层处于cocoa层之下,用到的很大一部分都是c语言的结构. 1.引入框架. #import & ...

  3. AVFoundation之录音及播放

    录音 在开始录音前,要把会话方式设置成AVAudioSessionCategoryPlayAndRecord //设置为播放和录音状态,以便可以在录制完之后播放录音AVAudioSession *se ...

  4. Android开发之PCM录音实时播放的实现方法 | 边录音边播放 |PCM录音播放无延迟 | 录音无杂音 | 录音无噪音

    先说下录音得开启录音权限 <uses-permission android:name="android.permission.RECORD_AUDIO" /> 然后录音 ...

  5. 智能会议系统(32)---WebRTC学习之三:录音和播放

    WebRTC学习之三:录音和播放 VoiceEngine中与录音和播放相关的头文件有五个,如下表所示: 头文件 包含的类 说明 voe_base.h VoiceEngineObserver Voice ...

  6. 单片机(Arduino)+FLASH+MIC+喇叭自制录音、播放器(二)

    单片机(Arduino)自制录音.播放器(二)播放器篇 前一篇给大家分享了录放机设计的大致流程,那么这篇我们将先专注于如何实现声音播放器,具体内容如下: 1. 声音播放器原理与知识点介绍 2. 硬件电 ...

  7. 树莓派3B+ 安装 `ReSpeaker 4-Mics Pi HAT` 声卡,录音与播放

    树莓派3B+ 安装 ReSpeaker 4-Mics Pi HAT 声卡,录音与播放 1. 查看默认声卡 利用cat /proc/asound/cards 可以查看系统出现的声卡,编号为0的为默认声卡 ...

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

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

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

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

最新文章

  1. 数据库2.0 -- 数据类型和数据表的基本操作
  2. SAP PM 入门系列17 - IB03 显示设备BOM
  3. 内部类不能有静态变量(除静态的对Static的理解)
  4. 【Boost】boost库中thread多线程详解10——condition条件变量
  5. C语言typedef关键字—伟大的缝纫师
  6. python内置数学函数库_在没有任何内置的求值函数或外部库的情况下用python解决数学问题...
  7. iOS开发使用UIKeyInput自定义密码输入框
  8. 简单介绍CUDA中loop unrolling(循环展开)技术
  9. 世界上最成熟、功能最全的加密库HELib
  10. go 中的关于命令行格式的使用
  11. Echarts教程_1-2 简介
  12. JS中点语法和中括号语法区别
  13. 创业投资——创新工场
  14. 敏捷开发之极限编程(XP)概念
  15. java word编辑_java实现word在线编辑及流转
  16. python设计迷宫_用Python制作迷宫GIF
  17. 硬盘的Smart信息说明
  18. C#与三菱PLC以太网通讯程序上位机源码 通过3E帧SLMP /MC协议与三菱FX5U/Q系列PLC通讯
  19. Hexo个人博客搭建教程
  20. 转载【数据集】计算机视觉,深度学习,数据挖掘数据集整理

热门文章

  1. 【Python爬虫学习实践】基于BeautifulSoup的网站解析及数据可视化
  2. fiddler怎么修改服务器返回参数并发送
  3. 读写应用程序数据-NSUserDefault、对象归档(NSKeyedArchiver)、文件操作
  4. HTTP 错误 404.13 - Not Found 请求筛选模块被配置为拒绝超过请求内容长度的请求
  5. 获取png格式的MNIST数据集
  6. kaggle中自己的notebook不见了
  7. RHEL7恢复.bashrc文件
  8. 04_ReplaceBlank
  9. 重置CentOS阿里云的mysql密码
  10. VSC++ 常量中出现符号