IOS利用AVFoundation框架实现录音和播放(AVAudioSession、AVAudioRecorder、AVAudioPlayer)

长平狐 发布于 2013/12/25 17:17
阅读 8K+
收藏 0

最近实现了一个简单功能,类似微信发送语音,按下录音,松开结束录音;并且可播放;

效果图:


Demo下载地址:

http://download.csdn.net/download/rhljiayou/6535125

需要导入

#import <AVFoundation/AVFoundation.h>

利用此框架中的

AVAudioRecorder和AVAudioPlayer来录音和播放

以下是AVAudioRecorder录音的使用方法:

- (IBAction)downAction:(id)sender {
    //按下录音
    if ([self canRecord]) {

        NSError *error = nil;
        //必须真机上测试,模拟器上可能会崩溃
        recorder = [[AVAudioRecorder alloc] initWithURL:[NSURL URLWithString:playName] settings:recorderSettingsDict error:&error];
        
        if (recorder) {
            //是否允许刷新电平表,默认是off
            recorder.meteringEnabled = YES;
            //创建文件,并准备录音
            [recorder prepareToRecord];
            //开始录音
            [recorder record];
            
            //启动定时器,为了更新电平
            timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(levelTimer:) userInfo:nil repeats:YES];
            
        } else
        {
            int errorCode = CFSwapInt32HostToBig ([error code]);
            NSLog(@"Error: %@ [%4.4s])" , [error localizedDescription], (char*)&errorCode);
            
        }
    }
   
}

- (IBAction)upAction:(id)sender {
    //松开 结束录音
    
    //录音停止
    [recorder stop];
    recorder = nil;
    //结束定时器
    [timer invalidate];
    timer = nil;
    //图片重置
    soundLodingImageView.image = [UIImage imageNamed:[volumImages objectAtIndex:0]];
    
}

以下是AVAudioPlayer播放器的使用方法:

- (IBAction)playAction:(id)sender {
    
    NSError *playerError;
    
    //播放
    player = nil;
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:playName] error:&playerError];
    
    if (player == nil)
    {
        NSLog(@"ERror creating player: %@", [playerError description]);
    }else{
        [player play];
    }
    
}

如果是7.0,第一次运行会提示,是否允许使用麦克风:


7.0需要设置:

if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending)
    {
        //7.0第一次运行会提示,是否允许使用麦克风
        AVAudioSession *session = [AVAudioSession sharedInstance];
        NSError *sessionError;
        //AVAudioSessionCategoryPlayAndRecord用于录音和播放
        [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
        if(session == nil)
            NSLog(@"Error creating session: %@", [sessionError description]);
        else
            [session setActive:YES error:nil];
    }


ok!完美,perfect!


转载来自任海丽博客






原文链接:http://blog.csdn.net/rhljiayou/article/details/15339335
加载中
返回顶部
顶部