通知短信+运营短信,5秒速达,支持群发助手一键发送🚀高效触达和通知客户 广告
[TOC] ### 录音功能实现 引入头文件 ``` #import <AVFoundation/AVFoundation.h> #import <AVKit/AVKit.h> ``` 在 **@interface** ViewController ()中添加录音类 ``` //录音 @property (strong, nonatomic) AVAudioRecorder \*recorder; ``` 在 @implementation ViewController下添加懒加载 ``` //懒加载 - (AVAudioRecorder *) recorder { if (!_recorder) { //路径 NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/record"]; //录音设置 NSMutableDictionary *settingDic = [[NSMutableDictionary alloc] init]; //采样率 [settingDic setValue:\[NSNumber numberWithInt:44100] forKey:AVSampleRateKey]; //录音格式 [settingDic setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey]; //录音通道 [settingDic setValue:[NSNumber numberWithInt:1] forKey:AVNumberOfChannelsKey]; //录音质量 [settingDic setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey]; _recorder = [[AVAudioRecorder alloc]initWithURL:[NSURL fileURLWithPath:path] settings:settingDic error:nil]; [_recorder prepareToRecord]; } return _recorder; } ``` 然后在关联按钮函数里实现录音功能: ``` - (IBAction)record:(UIButton *)sender { if (sender.isSelected == NO) { //开启录音 [self.recorder record]; sender.selected = YES; } else { //停止录音 [self.recorder stop]; sender.selected = NO; } } ``` ### 播放音频 音频文件的路径 可以是本地或是网址 在 **@interface** ViewController ()中添加播放音频类 ``` @property (strong, nonatomic)AVAudioPlayer *player; ``` 在 @implementation ViewController下添加懒加载 ``` - (AVAudioPlayer *)player{ if (!_player) { //音频文件路径 NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/record"]; //可以直接播放的本地音频路径 //NSString *path = [[NSBundle mainBundle]pathForResource:@"莲莲花"ofType:@"mp3"]; //播放器对象 _player = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:path] error:nil]; [_player prepareToPlay]; } return _player; } ``` 然后再player按钮关联的函数里实现播放功能: ``` - (IBAction)play:(UIButton *)sender { //播放 [self.player play]; } ```