声音的录制和播放一般采用的是系统的AVFoundation框架,所以首先需要导入
#import <AVFoundation/AVFoundation.h>
@implementation NSString (TimeString)
//格式化时间的显示格式
+(NSString*)timeStringForTimeInterval:(NSTimeInterval)timeInterval
{
NSInteger ti = (NSInteger)timeInterval;
NSInteger seconds = ti %60;
NSInteger minutes = (ti /60) % 60;
NSInteger hours = (ti /3600);
if (hours >0)
{
return [NSStringstringWithFormat:@"%02li:%02li:%02li", (long)hours, (long)minutes, (long)seconds];
}
else
{
return [NSStringstringWithFormat:@"%02li:%02li", (long)minutes, (long)seconds];
}
}
@end
@interface ViewController ()<AVAudioRecorderDelegate,AVAudioPlayerDelegate>
{
//Recording...
AVAudioRecorder *_audioRecorder;
NSString *_recordingFilePath;
//Playing
AVAudioPlayer *_audioPlayer;
BOOL _wasPlaying;
NSTimer *_timer;
NSString *_oldSessionCategory;
}
@property (strong,nonatomic)UIButton *recordBtn; //录音按钮
@end
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//Unique recording URL
NSString *fileName = [[NSProcessInfoprocessInfo]globallyUniqueString];
_recordingFilePath = [NSTemporaryDirectory()stringByAppendingPathComponent:[NSStringstringWithFormat:@"%@.m4a",fileName]];
NSMutableDictionary *recordSetting = [[NSMutableDictionaryalloc]init];
//设置录音的各种属性
[recordSetting setValue:[NSNumbernumberWithInt:kAudioFormatMPEG4AAC]forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumbernumberWithFloat:44100.0]forKey:AVSampleRateKey];
[recordSettingsetValue:[NSNumbernumberWithInt:2]forKey:AVNumberOfChannelsKey];
// Initiate and prepare the recorder
_audioRecorder = [[AVAudioRecorderalloc]initWithURL:[NSURLfileURLWithPath:_recordingFilePath]settings:recordSettingerror:nil];
_audioRecorder.delegate =self;
_audioRecorder.meteringEnabled =YES;
//录音按钮
_recordBtn = [UIButtonbuttonWithType:UIButtonTypeCustom];
_recordBtn.frame =CGRectMake(50,100,200, 30);
_recordBtn.backgroundColor = [UIColorlightGrayColor];
_recordBtn.titleLabel.font = [UIFontsystemFontOfSize:16];
[_recordBtnsetTitle:@"按住说话"forState:UIControlStateNormal];
[_recordBtnsetTitle:@"正在录音"forState:UIControlStateHighlighted];
[_recordBtnsetTitleColor:[UIColorblackColor]forState:UIControlStateNormal];
[_recordBtnsetTitleColor:[UIColorpurpleColor]forState:UIControlStateHighlighted];
//这里用UIControlEventTouchDown实现"按住说话"
[_recordBtnaddTarget:selfaction:@selector(recordAction:)forControlEvents:UIControlEventTouchDown];
[_recordBtnaddTarget:selfaction:@selector(stopRecordAction:)forControlEvents:UIControlEventTouchUpInside];
[self.viewaddSubview:_recordBtn];
}
//按下不松手,正在录音
- (void)recordAction:(UIButton *)btn
{
//检测录音的声音大小,做到显示当前声波大小的检测效果
_timer = [NSTimerscheduledTimerWithTimeInterval:-1target:selfselector:@selector(timerAction)userInfo:nilrepeats:YES];
//判断路径下有没有文件,有的话删掉
if ([[NSFileManagerdefaultManager]fileExistsAtPath:_recordingFilePath])
{
[[NSFileManagerdefaultManager]removeItemAtPath:_recordingFilePatherror:nil];
}
_oldSessionCategory = [[AVAudioSessionsharedInstance]category];
[[AVAudioSessionsharedInstance]setCategory:AVAudioSessionCategoryRecorderror:nil];
[_audioRecorderprepareToRecord];
[_audioRecorderrecord];
}
//当手指离开录音按钮,停止录音并关掉检测声波的定时器
- (void)stopRecordAction:(UIButton *)btn
{
[_audioRecorderstop];
[[AVAudioSessionsharedInstance]setCategory:_oldSessionCategoryerror:nil];
[_timerinvalidate];
}
- (void)timerAction
{
[_audioRecorderupdateMeters];
CGFloat normalizedValue =pow (10, [_audioRecorderaveragePowerForChannel:0] /20);
NSLog(@"-----%f",normalizedValue);
if (_audioRecorder.isRecording)
{
self.navigationItem.title = [NSStringtimeStringForTimeInterval:_audioRecorder.currentTime];
}
}
- (IBAction)playAction:(id)sender
{
// _oldSessionCategory = [[AVAudioSession sharedInstance] category];
// [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
_audioPlayer = [[AVAudioPlayeralloc]initWithContentsOfURL:[NSURLfileURLWithPath:_recordingFilePath]error:nil];
// _audioPlayer.delegate = self;
[_audioPlayerprepareToPlay];
[_audioPlayer play];
}