iOS 声音的录制和播放

声音的录制和播放一般采用的是系统的AVFoundation框架,所以首先需要导入

#import <AVFoundation/AVFoundation.h>

@implementation NSString (TimeString)


//格式化时间的显示格式

+(NSString*)timeStringForTimeInterval:(NSTimeInterval)timeInterval

{

   NSInteger ti = (NSInteger)timeInterval;

   NSInteger seconds = ti %60;

   NSInteger minutes = (ti /60) % 60;

   NSInteger hours = (ti /3600);

    

   if (hours >0)

    {

       return [NSStringstringWithFormat:@"%02li:%02li:%02li", (long)hours, (long)minutes, (long)seconds];

    }

   else

    {

       return  [NSStringstringWithFormat:@"%02li:%02li", (long)minutes, (long)seconds];

    }

}


@end


@interface ViewController ()<AVAudioRecorderDelegate,AVAudioPlayerDelegate>

{

    //Recording...

   AVAudioRecorder *_audioRecorder;

   NSString *_recordingFilePath;

    

    //Playing

   AVAudioPlayer *_audioPlayer;

   BOOL _wasPlaying;

    

   NSTimer *_timer;

   NSString *_oldSessionCategory;

}


@property (strong,nonatomic)UIButton *recordBtn;     //录音按钮


@end


- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    //Unique recording URL

    NSString *fileName = [[NSProcessInfoprocessInfo]globallyUniqueString];

    _recordingFilePath = [NSTemporaryDirectory()stringByAppendingPathComponent:[NSStringstringWithFormat:@"%@.m4a",fileName]];

    

    NSMutableDictionary *recordSetting = [[NSMutableDictionaryalloc]init];

    //设置录音的各种属性

    [recordSetting setValue:[NSNumbernumberWithInt:kAudioFormatMPEG4AAC]forKey:AVFormatIDKey];

    [recordSetting setValue:[NSNumbernumberWithFloat:44100.0]forKey:AVSampleRateKey];

    [recordSettingsetValue:[NSNumbernumberWithInt:2]forKey:AVNumberOfChannelsKey];

    

    // Initiate and prepare the recorder

    _audioRecorder = [[AVAudioRecorderalloc]initWithURL:[NSURLfileURLWithPath:_recordingFilePath]settings:recordSettingerror:nil];

    _audioRecorder.delegate =self;

    _audioRecorder.meteringEnabled =YES;

    

    //录音按钮

    _recordBtn = [UIButtonbuttonWithType:UIButtonTypeCustom];

   _recordBtn.frame =CGRectMake(50,100,200, 30);

    _recordBtn.backgroundColor = [UIColorlightGrayColor];

    _recordBtn.titleLabel.font = [UIFontsystemFontOfSize:16];

    [_recordBtnsetTitle:@"按住说话"forState:UIControlStateNormal];

    [_recordBtnsetTitle:@"正在录音"forState:UIControlStateHighlighted];

    [_recordBtnsetTitleColor:[UIColorblackColor]forState:UIControlStateNormal];

    [_recordBtnsetTitleColor:[UIColorpurpleColor]forState:UIControlStateHighlighted];

    //这里用UIControlEventTouchDown实现"按住说话"

    [_recordBtnaddTarget:selfaction:@selector(recordAction:)forControlEvents:UIControlEventTouchDown];

    [_recordBtnaddTarget:selfaction:@selector(stopRecordAction:)forControlEvents:UIControlEventTouchUpInside];

    [self.viewaddSubview:_recordBtn];

}

//按下不松手,正在录音

- (void)recordAction:(UIButton *)btn

{

    //检测录音的声音大小,做到显示当前声波大小的检测效果

    _timer = [NSTimerscheduledTimerWithTimeInterval:-1target:selfselector:@selector(timerAction)userInfo:nilrepeats:YES];

    

    //判断路径下有没有文件,有的话删掉

    if ([[NSFileManagerdefaultManager]fileExistsAtPath:_recordingFilePath])

    {

        [[NSFileManagerdefaultManager]removeItemAtPath:_recordingFilePatherror:nil];

    }

    

    _oldSessionCategory = [[AVAudioSessionsharedInstance]category];

    [[AVAudioSessionsharedInstance]setCategory:AVAudioSessionCategoryRecorderror:nil];

    [_audioRecorderprepareToRecord];

    [_audioRecorderrecord];

}


//当手指离开录音按钮,停止录音并关掉检测声波的定时器

- (void)stopRecordAction:(UIButton *)btn

{

    [_audioRecorderstop];

    [[AVAudioSessionsharedInstance]setCategory:_oldSessionCategoryerror:nil];

    [_timerinvalidate];

}

- (void)timerAction

{

    [_audioRecorderupdateMeters];

   CGFloat normalizedValue =pow (10, [_audioRecorderaveragePowerForChannel:0] /20);

   NSLog(@"-----%f",normalizedValue);

    

    if (_audioRecorder.isRecording)

    {

        self.navigationItem.title = [NSStringtimeStringForTimeInterval:_audioRecorder.currentTime];

    }

}


- (IBAction)playAction:(id)sender

{

//    _oldSessionCategory = [[AVAudioSession sharedInstance] category];

//    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

    _audioPlayer = [[AVAudioPlayeralloc]initWithContentsOfURL:[NSURLfileURLWithPath:_recordingFilePath]error:nil];

//    _audioPlayer.delegate = self;

    [_audioPlayerprepareToPlay];

    [_audioPlayer play];

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值