iOS录音和播放

录音要借助于AVAudioPlayer ,它是 AVFoundation.framework 中定义的一个类,所以使用要先在工程中引入AVFoundation.framework。我们可以把 AVAudioPlayer看作是一个高级的播放器,它支持广泛的音频格式。

MainViewController.h

#import 
#import 

@interface MainViewController : UIViewController
{
    AVAudioRecorder *recorder;
    NSTimer *timer;
    NSURL *urlPlay;
}

@property(nonatomic,retain)UIButton *btn;
@property(nonatomic,retain)UIButton *playButton;
@property(nonatomic,retain)UIImageView *imageView;
@property(nonatomic,retain)AVAudioPlayer *avPlay;

@end

MainViewController.m

#import "MainViewController.h"

@interface MainViewController ()

@end

@implementation MainViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self audio];
    self.btn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.btn.frame=CGRectMake(50, 300, 100, 80);
    [self.btn setTitle:@"录音" forState:UIControlStateNormal];
    self.btn.backgroundColor=[UIColor redColor];
    self.btn.alpha=0.6;
    //按录音按钮的方法
    [self.btn addTarget:self action:@selector(btnDown:) forControlEvents:UIControlEventTouchDown];
    //松开录音按钮的方法
    [self.btn addTarget:self action:@selector(btnUP:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.btn];

    self.playButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.playButton.frame=CGRectMake(190, 300, 100, 80);
    [self.playButton setTitle:@"播放" forState:UIControlStateNormal];
    self.playButton.backgroundColor=[UIColor redColor];
    self.playButton.alpha=0.6;
    //按播放按钮的方法
    [self.playButton addTarget:self action:@selector(playButtonAction:) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:self.playButton];

    self.imageView=[[UIImageView alloc]initWithFrame:CGRectMake(80, 30, 160, 200)];
    self.imageView.backgroundColor=[UIColor greenColor];

    [self.view addSubview:self.imageView];
}

#pragma mark - 录音按钮按下的方法

-(void)btnDown:(UIButton *)sender
{
    //创建录音文件,准备录音
    if ([recorder prepareToRecord])
    {
        NSFileManager *fm = [NSFileManager defaultManager];
        [fm createFileAtPath:urlPlay.description contents:nil attributes:nil];
        //开始
        [recorder record];
        //设置定时监测
        timer=[NSTimer scheduledTimerWithTimeInterval:0 target:self selector:@selector(detectionVoice:) userInfo:nil repeats:YES];
        NSLog(@"down");
    }
}

//这里其实可以根据音量大小的比例 用一个view的高度来显示
-(void)detectionVoice:(NSTimer *)time
{
    [recorder updateMeters];//刷新音量数据
    //获取音量的平均值  [recorder averagePowerForChannel:0];
    //音量的最大值  [recorder peakPowerForChannel:0];
    double lowPassResults=pow(10, (0.05*[recorder peakPowerForChannel:0]));
    NSLog(@"%lf",lowPassResults);
    //图片 小->大
    if (01)//录制时间<1不发送
    {
        NSLog(@"发送出去");
    }
    else
    {
        //删除记录文件-之前的文件
        [recorder deleteRecording];
    }

    [recorder stop];
    [timer invalidate];
    [self updateImage];
}

#pragma -mark - 播放按钮的方法

-(void)playButtonAction:(UIButton *)sender
{
    if (self.avPlay.playing)
    {
        [self.avPlay stop];
        return;
    }

    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    AVAudioPlayer *player=[[AVAudioPlayer alloc]initWithContentsOfURL:urlPlay error:nil];
    self.avPlay=player;
    [self.avPlay play];
}

-(void)audio
{
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryRecord error:nil];
    //录音设置
    NSMutableDictionary *recordSetting=[[NSMutableDictionary alloc]init];
    //设置录音格式 AVFormatIDKey==kAudioFormatLinearPCM
    [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
    //设置录音采样率(Hz)如:AVSampleRateKey==8000/44100/96000(影响音频的质量)
    [recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];

    //录音通道数
    [recordSetting setValue:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];
    //[recordSetting setObject:[NSNumber numberWithInt:12800] forKey:AVEncoderBitRateKey];//解码率
    //线性采样位数 8/16/24/32
    [recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];

    //录音质量
    [recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
    NSString *strUrl=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];
    NSURL *url=[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/lll.caf",strUrl]];
    NSLog(@"%@",url);
    urlPlay=url;
    NSError *error;
    //初始化
    recorder=[[AVAudioRecorder alloc]initWithURL:url settings:recordSetting error:&error];
    //开启音量检测
    recorder.meteringEnabled=YES;
    recorder.delegate=self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

图片资源源自网络

image
image
image
image
image
image
image
image
image
image
image
image
image
image

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