简单的实现了AVAudioRecorder (录音)和AVAudioPlayer(播放)功能.
#import <AVFoundation/AVFoundation.h>
#import "ViewController.h"
@interface ViewController ()<AVAudioRecorderDelegate>{
AVAudioRecorder *recorder;
AVAudioPlayer *Aplayer;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//设置文件保存路径
-(NSURL *)url
{
//获取document目录的路径
NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
//获取音频文件的保存路径
NSString *strPath = [path stringByAppendingPathComponent:@"lwsound.wav"];
//设置网络路径
NSURL *url = [NSURL fileURLWithPath:strPath];
return url;
}
//开始录制
- (IBAction)clickRecord:(id)sender {
//创建一个NSDictionary,用于保存录制属性
NSMutableDictionary *Mdic = [[NSMutableDictionary alloc] init];
//设置录制音频的格式
[Mdic setObject:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
//设置录制音频的采样率
[Mdic setObject:[NSNumber numberWithFloat:44100] forKey:AVSampleRateKey];
//设置录制音频的通道数
[Mdic setObject:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];
//设置录制音频的每个样点的位数
[Mdic setObject:[NSNumber numberWithInt:24] forKey:AVLinearPCMBitDepthKey];
//设置录制音频采用高位优先的记录格式
[Mdic setObject:[NSNumber numberWithBool:YES] forKey:AVLinearPCMIsBigEndianKey];
//设置采样信号采用浮点数
[Mdic setObject:[NSNumber numberWithBool:YES] forKey:AVLinearPCMIsFloatKey];
// 初始化AVAudioRecorder
NSError *err = nil;
recorder = [[AVAudioRecorder alloc] initWithURL:[self url] settings:Mdic error:&err];
//开始录制
[recorder record];
}
//停止录制
- (IBAction)clickStop:(id)sender {
//设置代理
recorder.delegate = self;
[recorder stop];
}
//开始播放录屏
- (IBAction)clickPlay:(id)sender {
//创建AVAudioPlayer对象
Aplayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[self url] error:nil];
// 开始播放
[Aplayer play];
}
//设置录制音频的代理方法
- (void)audioRecorderBeginInterruption:(AVAudioRecorder *)recorder
{
NSLog(@"被中断!");
}
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)aRecorder
successfully:(BOOL)flag
{
if(flag)
{
NSLog(@"录制完成!!");
}else{
NSLog(@"录制失败!!");
}
}