iOS--播放声音(AVAudioPlayer)、录音(AVAudioRecorder)

播放音频

 

首先在导入框架:

#import <AVFoundation/AVFoundation.h>

 

//01  加载音频路径

 

NSString *str=[[NSBundle mainBundle] pathForResource:@"半点心_草蜢" ofType:@"mp3"];  

    NSURL *musicUrl=[NSURL fileURLWithPath:str];

//02 创建AVAudioPlayer的对象

  AVAudioPlayer*   _player=[[AVAudioPlayer alloc] initWithContentsOfURL:musicUrl error:nil];

 

//03 准备播放

//因为有些音频可能过大,一次性加载到内存可能会耗时过长,所以先使用准备播放,就是提前加载音频到内存中

      [_player prepareToPlay];

 

//开始播放

    [_player play];

 

//暂停播放

    [_player pause];

 

 

录音:

 

 

首先在导入框架:

#import <AVFoundation/AVFoundation.h>

 

//01 创建录音保存路径

   //保存到沙盒路径下

    NSString* path = [NSString stringWithFormat:@"%@/Documents/luyin", NSHomeDirectory()];

    NSURL* url = [NSURL fileURLWithPath:path];

 

// 02  对录音进行设置

 

以/*******————*****/开始,到/*******————*****/结束之间的代码可以完全一样,因为录音设置的对象太多了,以下设置方式,已经可以实现大多数的录音效果了,所以推荐没有特殊情况,不要修改,直接复制即可

 

/*******————*****/

    //录音设置

    NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc]init];

    //设置录音格式  AVFormatIDKey==kAudioFormatLinearPCM

    [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];

    //设置录音采样率(Hz) 如:AVSampleRateKey==8000/44100/96000(影响音频的质量)

    [recordSetting setValue:[NSNumber numberWithFloat:44100] forKey:AVSampleRateKey];

    //录音通道数  1 或 2

    [recordSetting setValue:[NSNumber numberWithInt:1] forKey:AVNumberOfChannelsKey];

    //线性采样位数  8、16、24、32

    [recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];

    //录音的质量

    [recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];

 

/*******————*****/

 

//03 创建AVAudioRecorder对象

//初始化录音

   AVAudioRecorder* _recorder = [[AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:nil];

 

 

//04  准备录音

 

      //准备录音

    [_recorder prepareToRecord];

 

 

//开始录音

    [_recorder record];

//停止录音

  [_recorder stop];

 

完整代码工程:

第一个界面:播放音频

sstoryboard截图:

 

 对应代码:

#import "AZViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "AZSecondViewController.h"
@interface AZViewController ()
{
    AVAudioPlayer *_player;
    NSTimer *_timer;
}
@property (weak, nonatomic) IBOutlet UISlider *proSlider;
@property (weak, nonatomic) IBOutlet UISlider *voiceSlider;
@property (weak, nonatomic) IBOutlet UISlider *panSlider;
@property (weak, nonatomic) IBOutlet UISlider *speedSlider;

@property (weak, nonatomic) IBOutlet UIProgressView *pv2;

@property (weak, nonatomic) IBOutlet UIProgressView *pv1;


- (IBAction)play:(id)sender;
- (IBAction)puse:(id)sender;
- (IBAction)next:(id)sender;

@end

@implementation AZViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    self.navigationItem.title=@"播放声音";
    
    NSString *str=[[NSBundle mainBundle] pathForResource:@"半点心_草蜢" ofType:@"mp3"];
   
    NSURL *musicUrl=[NSURL fileURLWithPath:str];

    _player=[[AVAudioPlayer alloc] initWithContentsOfURL:musicUrl error:nil];
    
    //准备播放
    [_player prepareToPlay];
    
    
    //开启变速
    [_player setEnableRate:YES];
    //开启峰值
    _player.meteringEnabled=YES;
    
    
    [self.proSlider addTarget:self action:@selector(setProcess) forControlEvents:UIControlEventValueChanged];
    
    [self.voiceSlider addTarget:self action:@selector(changeVoice) forControlEvents:UIControlEventValueChanged];
    
    [self.panSlider addTarget:self action:@selector(changePan) forControlEvents:UIControlEventValueChanged];
    
    [self.speedSlider addTarget:self action:@selector(changeSpeed) forControlEvents:UIControlEventValueChanged];
}

-(void)setProcess
{
    //设置进度
    _player.currentTime=_player.duration*self.proSlider.value;
}
-(void)changeVoice
{
    //设置声音
    _player.volume=self.voiceSlider.value;
}
-(void)changePan
{
    _player.pan=self.panSlider.value;
}
-(void)changeSpeed
{
    //设置播放速度
    _player.rate=self.speedSlider.value;
}

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

- (IBAction)play:(id)sender
{
    //开始播放
    [_player play];
    if (!_timer) {
       _timer=[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timeCome) userInfo:nil repeats:YES];
    }
    [_timer setFireDate:[NSDate distantPast]];
    
}
-(void)timeCome
{
    //进度=当前时间/总时间
    float pro=_player.currentTime/_player.duration;
    [self.proSlider setValue:pro animated:YES];
    
    //刷新峰值
    [_player updateMeters];
    //最大峰值
    float peakValue=[_player peakPowerForChannel:0];
    
    //平均值
    float avgValue=[_player averagePowerForChannel:0];
    
    
    //打印查看该音乐的最大峰值,和平均峰值的范围
    // NSLog(@"%f--%f",peakValue,avgValue);
    //该音乐一般为  -20,有的音乐可能不同
    [_pv1 setProgress:(peakValue+20)/20 animated:YES];
    [_pv2 setProgress:(avgValue+20)/20 animated:YES];
}

- (IBAction)puse:(id)sender
{
    //暂停播放
    [_player pause];
    //暂停定时器
    [_timer setFireDate:[NSDate distantFuture]];
    
}

- (IBAction)next:(id)sender
{
    AZSecondViewController *secondVC=[[AZSecondViewController alloc] init];
    [self.navigationController pushViewController:secondVC animated:YES];
}
@end

 第二个界面:录音

界面:

代码:

#import "AZSecondViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface AZSecondViewController ()
{
    UIButton *_button;
    AVAudioPlayer* _player;
    AVAudioRecorder* _recorder;
}
@end

@implementation AZSecondViewController

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

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor=[UIColor whiteColor];
    self.navigationItem.title=@"录音";
    _button=[UIButton buttonWithType:UIButtonTypeCustom];
    _button.frame=CGRectMake(100, 100, 100, 20);
    [_button setTitle:@"开始录音" forState:UIControlStateNormal];
    [_button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [_button addTarget:self action:@selector(startRecond) forControlEvents:UIControlEventTouchDown];//按下开始响应事件
 
    [_button addTarget:self action:@selector(stopRecond) forControlEvents:UIControlEventTouchUpInside];//松开的响应事件
    [self.view addSubview:_button];
    //保存到沙盒路径下
    NSString* path = [NSString stringWithFormat:@"%@/Documents/luyin", NSHomeDirectory()];
    NSURL* url = [NSURL fileURLWithPath:path];
    
    //录音设置
    NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc]init];
    //设置录音格式  AVFormatIDKey==kAudioFormatLinearPCM
    [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
    //设置录音采样率(Hz) 如:AVSampleRateKey==8000/44100/96000(影响音频的质量)
    [recordSetting setValue:[NSNumber numberWithFloat:44100] forKey:AVSampleRateKey];
    //录音通道数  1 或 2
    [recordSetting setValue:[NSNumber numberWithInt:1] forKey:AVNumberOfChannelsKey];
    //线性采样位数  8、16、24、32
    [recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
    //录音的质量
    [recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
    
    
    //初始化录音
    _recorder = [[AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:nil];
    //准备录音
    [_recorder prepareToRecord];
    //[_recorder setMeteringEnabled:YES];
    
    
}
-(void)startRecond
{
    [_button setTitle:@"录音中...." forState:UIControlStateNormal];
    [_recorder record];

}
-(void)stopRecond
{
    [_button setTitle:@"开始录音" forState:UIControlStateNormal];
    [_recorder stop];
    
    NSString* path = [NSString stringWithFormat:@"%@/Documents/luyin", NSHomeDirectory()];
    NSURL* url = [NSURL fileURLWithPath:path];
    _player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    [_player prepareToPlay];
    [_player play];

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

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end