#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>//注意导入引用库
@interface ViewController ()<AVAudioRecorderDelegate>
{
AVAudioRecorder *recorder;
AVAudioPlayer *audioPlayer;
BOOL recording;
NSURL *tmpFile;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//录制
UIButton *recording1 = [[UIButton alloc]init];
recording1.backgroundColor = [UIColor lightGrayColor];
recording1.frame = CGRectMake(50, 100, 70, 70);
[recording1 setTitle:@"录制" forState:UIControlStateNormal];
[recording1 addTarget:self action:@selector(recordingbtnClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:recording1];
//播放
UIButton *broadcast = [[UIButton alloc]init];
broadcast.frame = CGRectMake(150, 100, 70, 70);
broadcast.backgroundColor = [UIColor lightGrayColor];
[broadcast setTitle:@"播放" forState:UIControlStateNormal];
[broadcast addTarget:self action:@selector(broadcastBtnClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:broadcast];
}
//录制
- (void)recordingbtnClick:(UIButton *)sender{
//单列创建 音频会议
AVAudioSession * audioSession = [AVAudioSession sharedInstance];
if (!recording) {
recording = YES;
[audioSession setCategory:AVAudioSessionCategoryRecord error:nil];
[audioSession setActive:YES error:nil];
[sender setTitle:@"停止" forState:UIControlStateNormal];
NSDictionary *setting = [[NSDictionary alloc] initWithObjectsAndKeys: [NSNumber numberWithFloat: 44100.0],AVSampleRateKey, [NSNumber numberWithInt: kAudioFormatLinearPCM],AVFormatIDKey, [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey, [NSNumber numberWithInt: 2], AVNumberOfChannelsKey, [NSNumber numberWithBool:NO],AVLinearPCMIsBigEndianKey, [NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,nil];
//URL 沙盒路径+文件名 这里文件名最好用时间 因为时间不会重复 避免覆盖
tmpFile = [NSURL fileURLWithPath:
[NSTemporaryDirectory() stringByAppendingPathComponent:
[NSString stringWithFormat: @"%@.%@",
@"shishi",
@"wav"]]];
recorder = [[AVAudioRecorder alloc] initWithURL:tmpFile settings:setting error:nil];
[recorder setDelegate:self];
[recorder prepareToRecord];
[recorder record];
} else {
recording = NO;
[audioSession setActive:NO error:nil];
[recorder stop];
[sender setTitle:@"录音" forState:UIControlStateNormal];
}
}
//播放
- (void)broadcastBtnClick{
NSError *error;
audioPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:tmpFile
error:&error];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
audioPlayer.volume=1;
if (error) {
NSLog(@"error:%@",[error description]);
return;
}
//准备播放
[audioPlayer prepareToPlay];
//播放
[audioPlayer play];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end