ios之录音+播放

简单的实现了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(@"录制失败!!");
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值