录音与播放

#import "ViewController.h"
//导入AVFoundation框架
#import 
@interface ViewController ()
{
    NSURL *recordURL;
    AVAudioPlayer *player;
    AVAudioRecorder *recorder;
}
@end

@implementation ViewController

设置button状态为UIControlEventTouchDown开始录音

- (IBAction)startRecord:(UIButton *)sender {
    //把之前录音机设为空 
    recorder = nil;
    //删除已有的声音文件
    NSFileManager *manager = [NSFileManager defaultManager];
    //通过地址
    [manager removeItemAtURL:_soundFileURL error:nil];
    //把音频回话设置为录音模式
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryRecord error:nil];
    //创建设置
     /*
     1 声音的格式
     2 采样率
     3 声道数 2
     4 采样位数
     5 内存的组织方式(大端,小端)
     6 编码质量
     */
    NSDictionary *setting = @{AVFormatIDKey : [NSNumber numberWithInt:kAudioFormatMPEG4AAC],
                              AVSampleRateKey : @1000,
                              AVNumberOfChannelsKey : @2,
                              AVLinearPCMBitDepthKey : @16,
                              AVLinearPCMIsBigEndianKey : @NO,
                              AVLinearPCMIsFloatKey : @NO,
                              AVEncoderAudioQualityKey : [NSNumber numberWithInt:AVAudioQualityMedium]
                              };
    //创建录音器
    recorder = [[AVAudioRecorder alloc] initWithURL:recordURL settings:setting error:nil];
    [recorder prepareToRecord];
    //录音器开始录音
    [recorder record];
}

设置button状态为UIControlEventTouchUpInside停止录音

- (IBAction)stopRecord:(UIButton *)sender {
    //停止录音,是录音机停止
    [recorder stop];
    //把录音机设为空
    recorder = nil;
    //还原音频会话为播放模式
    [[AVAudioSession sharedInstance]setCategory:AVAudioSessionCategorySoloAmbient error:nil];
}

播放录音


- (IBAction)playRecord:(UIButton *)sender {
    //把之前播放器设为空
    player = nil;
    //创建播放器
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:recordURL error:nil];
    [player prepareToPlay];
    [player play];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //创建录音文件
    NSString *recordString = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/sound.acc"];
    //获取文件地址
    recordURL = [NSURL fileURLWithPath:recordString];

}

@end

你可能感兴趣的:(录音与播放)