您的位置:首页 > 移动开发 > IOS开发

iOS实现录音与播放功能

2015-04-02 11:21 627 查看
视同控制器.h

//

// ACYL_RecordViewController.h

// Ancun

//

// Created by Dubai on 15/4/1.

//

//

#import <UIKit/UIKit.h>

#import <AudioToolbox/AudioToolbox.h>

#import <AVFoundation/AVFoundation.h>

@interface ACYL_RecordViewController :
UIViewController<AVAudioRecorderDelegate>

{

AVAudioRecorder *recorder;

NSTimer *timer;

NSURL *urlPlay;
}

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

@property (strong,
nonatomic) UIButton *playBtn;//播放按钮

@property (strong ,nonatomic)
UIImageView *imageViewWave;//显示波形图的视图

@property (strong,
nonatomic) AVAudioPlayer *avPlay;

@end

视图控制器.m

//

// ACYL_RecordViewController.m

// Ancun

//

// Created by Dubai on 15/4/1.

//

//

#import "ACYL_RecordViewController.h"

#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)

#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)

@interface
ACYL_RecordViewController ()
{

NSTimer *timeRecordNow;//录音时间戳

UILabel *timeLabel;//显示时间戳

}

@end

@implementation ACYL_RecordViewController

-(void)viewWillAppear:(BOOL)animated
{

self.view.backgroundColor = [UIColor
whiteColor];

self.tabBarController.tabBar.translucent =
NO;
}

-(void)viewDidLoad
{

[super
viewDidLoad];

AVAudioSession *audioSession = [AVAudioSession
sharedInstance];

[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord
error:nil];
[audioSession
setActive:YES
error:nil];

if ([audioSession
respondsToSelector:@selector(requestRecordPermission:)]) {
[audioSession
performSelector:@selector(requestRecordPermission:)
withObject:^(BOOL granted) {

if (granted) {

// Microphone enabled code
}

else {

// Microphone disabled code
}
}];
}

[recorder
prepareToRecord];

recorder.meteringEnabled =
YES;
[recorder
record];

[self
audio];//设置录音

//波形图

self.imageViewWave = [[UIImageView
alloc]
initWithFrame:CGRectMake(SCREEN_WIDTH -SCREEN_WIDTH/1.2,
80.0,
SCREEN_WIDTH/1.5,
200)];

self.imageViewWave.backgroundColor = [UIColor
redColor];

[self.view
addSubview:self.imageViewWave];

self.recordBtn = [UIButton
buttonWithType:(UIButtonTypeSystem)];

self.recordBtn.frame =
CGRectMake(SCREEN_WIDTH/6,
self.imageViewWave.frame.origin.y+self.imageViewWave.frame.size.height+30,
60,
40);

[self.recordBtn
setTitle:@"录音"
forState:(UIControlStateNormal)];

// [self.recordBtn addTarget:self action:@selector(didRecordBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];

[self.recordBtn
addTarget:self
action:@selector(btnDown:)
forControlEvents:UIControlEventTouchDown];

[self.recordBtn
addTarget:self
action:@selector(btnUp:)
forControlEvents:UIControlEventTouchUpInside];

[self.recordBtn
addTarget:self
action:@selector(btnDragUp:)
forControlEvents:UIControlEventTouchDragExit];
[self.view
addSubview:self.recordBtn];

//播放按钮

self.playBtn = [UIButton
buttonWithType:(UIButtonTypeSystem)];

self.playBtn.frame =
CGRectMake(self.recordBtn.frame.origin.x+130,
self.recordBtn.frame.origin.y,
self.recordBtn.frame.size.width,
self.recordBtn.frame.size.height);

[self.playBtn
setTitle:@"播放"
forState:(UIControlStateNormal)];

[self.playBtn
addTarget:self
action:@selector(playRecordSound:)
forControlEvents:(UIControlEventTouchDown)];
[self.view
addSubview:self.playBtn];

//停止按钮

UIButton *stopBtn = [UIButton
buttonWithType:(UIButtonTypeSystem)];
stopBtn.frame =
CGRectMake(self.recordBtn.frame.origin.x
,
self.recordBtn.frame.origin.y+self.recordBtn.frame.size.height+30,
60, 40);

[stopBtn setTitle:@"stop"
forState:(UIControlStateNormal)];

[stopBtn addTarget:self
action:@selector(didStopBtnAction:)
forControlEvents:(UIControlEventTouchUpInside)];
[self.view
addSubview:stopBtn];

//暂停按钮

UIButton *paseBtn = [UIButton
buttonWithType:(UIButtonTypeSystem)];
[paseBtn
setFrame:CGRectMake(self.playBtn.frame.origin.x,self.playBtn.frame.origin.y
+ self.playBtn.frame.size.height+30,
60, 40)];

[paseBtn setTitle:@"pase"
forState:(UIControlStateNormal)];

[paseBtn addTarget:self
action:@selector(didPaseBtnAction:)
forControlEvents:(UIControlEventTouchUpInside)];
[self.view
addSubview:paseBtn];

//录音时间戳

timeRecordNow = [NSTimer
scheduledTimerWithTimeInterval:1.0f
target:self

selector:@selector(timerFunc)
userInfo:nil
repeats:YES];

//显示时间戳

timeLabel = [[UILabel
alloc] initWithFrame:CGRectMake(30,
450,
250, 50)];

timeLabel.backgroundColor = [UIColor
orangeColor];
[self.view
addSubview:timeLabel];

}

//显示时间戳
- (void)timerFunc
{

NSDate *datenow = [NSDate
date];//现在时间,你可以输出来看下是什么格式

NSTimeZone *zone = [NSTimeZone
systemTimeZone];

NSInteger interval = [zone
secondsFromGMTForDate:datenow];

NSDate *localeDate = [datenow
dateByAddingTimeInterval: interval];

NSLog(@"------%@", localeDate);

NSDateFormatter *dateFrame = [[NSDateFormatter
alloc ]init ];

[dateFrame setDateFormat:@"yyyy年MM月dd日HH点mm分ss秒"];

NSDate *date = datenow;

NSString *timeString = [dateFrame
stringFromDate:date];//[NSDate date];

NSLog(@"************%@",timeString);
[timeLabel
setText:timeString];
}

- (void)requestRecordPermission:(id)sender
{

NSLog(@"hello");

//[AVAudioSessionCategoryPlayback set]

}

//暂停
- (void)didPaseBtnAction:(id)sender
{

[recorder
pause];

[timer
invalidate];

}

//停止
- (void)didStopBtnAction:(id)sender
{

[recorder
stop];

[timer
invalidate];

}
- (void)audio
{

//录音设置

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];

NSFileManager *filePathmanger = [NSFileManager
defaultManager];

NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,
NSUserDomainMask, YES)lastObject];

NSString *filePath = [cachesPath
stringByAppendingPathComponent:@"/Record"];

[filePathmanger createDirectoryAtPath:filePath
withIntermediateDirectories:YES
attributes:nil
error:nil];

NSURL *url = [NSURL
fileURLWithPath:[NSString
stringWithFormat:@"/%@/lll.aac", filePath]];

NSData *dataRecord = [NSData
dataWithContentsOfURL:url];
[dataRecord
writeToFile:filePath
atomically:YES];

urlPlay = url;

NSError *error;

//初始化

recorder = [[AVAudioRecorder
alloc]initWithURL:url
settings:recordSetting
error:&error];

//开启音量检测

recorder.meteringEnabled =
YES;

recorder.delegate =
self;

// //获取录音的时间

// AVURLAsset* audioAsset =[AVURLAsset URLAssetWithURL:url options:nil];

//

// CMTime audioDuration = audioAsset.duration;

//

// float audioDurationSeconds =CMTimeGetSeconds(audioDuration);

// NSLog(@"%f",audioDurationSeconds);

// NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:1970];

// NSTimeInterval a=[dat timeIntervalSince1970];

// NSString *timeString = [NSString stringWithFormat:@"%f", a];//转为字符型

// NSLog(@"==============timestring = %@",timeString);

// NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式

// NSTimeZone *zone = [NSTimeZone systemTimeZone];

// NSInteger interval = [zone secondsFromGMTForDate:datenow];

// NSDate *localeDate = [datenow dateByAddingTimeInterval: interval];

// NSLog(@"------%@", localeDate);

//

// NSDateFormatter *dateFrame = [[NSDateFormatter alloc ]init ];

// [dateFrame setDateFormat:@"yyyy年MM月dd日HH点mm分ss秒"];

// NSDate *date = datenow;

// NSString *timeString = [dateFrame stringFromDate:date];//[NSDate date];

// NSLog(@"************%@",timeString);

//

// UILabel *timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 450, 250, 50)];

// timeLabel.text = [NSString stringWithFormat:@"%@",timeString];

// timeLabel.backgroundColor = [UIColor orangeColor];

// [self.view addSubview:timeLabel];

// //3.把时间戳转化为时间的方法

// NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:1363948516];

// NSLog(@"==========1363948516 = %@",confromTimesp);

//

}

//按下去的时候
- (void)btnDown:(UIButton *)sender
{

//创建录音文件,准备录音

if ([recorder
prepareToRecord]) {

//开始
[recorder
record];
}

//设置定时检测

timer = [NSTimer
scheduledTimerWithTimeInterval:0
target:self
selector:@selector(detectionVoice)
userInfo:nil
repeats:YES];
}

//离开按钮的时候
- (void)btnUp:(id)sender
{

double cTime = recorder.currentTime;

if (cTime > 2) {//如果录制时间<2
不发送

NSLog(@"发出去");

// NSString *cachesPaths = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];

// NSLog(@"caches patyh = %@",cachesPaths);

//

}else {

UIAlertView *alter = [[UIAlertView
alloc] initWithTitle:@"提示"
message:@"录音小于两秒,无法保存"
delegate:self
cancelButtonTitle:@"确定"
otherButtonTitles:nil,
nil];
[alter
show];

//删除记录的文件

[recorder
deleteRecording];

//删除存储的
}

//创建

NSFileManager *fileManager = [NSFileManager
defaultManager];

//找路径

NSString *cachespath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,
NSUserDomainMask, YES)lastObject];

//拼接新文件的路径

NSString *filePath = [cachespath
stringByAppendingPathComponent:@"RecordPath/path2"];

[fileManager createDirectoryAtPath:filePath
withIntermediateDirectories:YES
attributes:nil
error:nil];

NSLog(@"file path = %@",filePath);

NSString *hea = @"hello";

NSString *filepathRecord = [filePath
stringByAppendingPathComponent:@"saveRecord.txt"];

[hea writeToFile:filepathRecord
atomically:YES
encoding:NSUTF8StringEncoding
error:nil];

//从沙盒里面把文件删除
[fileManager
removeItemAtPath:filePath
error:nil];

[recorder
stop];

[timer
invalidate];
}

- (void)btnDragUp:(id)sender
{

//删除录制文件

[recorder
deleteRecording];
[recorder
stop];

[timer
invalidate];

NSLog(@"取消发送");
}

//播放按钮
- (void)playRecordSound:(id)sender
{
[recorder
stop];

[timer
invalidate];

if (self.avPlay.playing) {
[self.avPlay
stop];

return;
}

AVAudioPlayer *player = [[AVAudioPlayer
alloc]initWithContentsOfURL:urlPlay
error:nil];

self.avPlay = player;
[self.avPlay
play];
}

- (void)detectionVoice
{

[recorder
updateMeters];//刷新音量数据

//获取音量的平均值 [recorder averagePowerForChannel:0];

//音量的最大值 [recorder peakPowerForChannel:0];

double lowPassResults =
pow(10, (0.05 * [recorder
peakPowerForChannel:0]));

NSLog(@"%lf",lowPassResults);

//最大50 0

//图片
小-》大

if (0<lowPassResults<=0.06) {

[self.imageViewWave
setImage:[UIImage
imageNamed:@"record_animate_01.png"]];
}else
if (0.06<lowPassResults<=0.13) {

[self.imageViewWave
setImage:[UIImage
imageNamed:@"record_animate_02.png"]];
}else
if (0.13<lowPassResults<=0.20) {

[self.imageViewWave
setImage:[UIImage
imageNamed:@"record_animate_03.png"]];
}else
if (0.20<lowPassResults<=0.27) {

[self.imageViewWave
setImage:[UIImage
imageNamed:@"record_animate_04.png"]];
}else
if (0.27<lowPassResults<=0.34) {

[self.imageViewWave
setImage:[UIImage
imageNamed:@"record_animate_05.png"]];
}else
if (0.34<lowPassResults<=0.41) {

[self.imageViewWave
setImage:[UIImage
imageNamed:@"record_animate_06.png"]];
}else
if (0.41<lowPassResults<=0.48) {

[self.imageViewWave
setImage:[UIImage
imageNamed:@"record_animate_07.png"]];
}else
if (0.48<lowPassResults<=0.55) {

[self.imageViewWave
setImage:[UIImage
imageNamed:@"record_animate_08.png"]];
}else
if (0.55<lowPassResults<=0.62) {

[self.imageViewWave
setImage:[UIImage
imageNamed:@"record_animate_09.png"]];
}else
if (0.62<lowPassResults<=0.69) {

[self.imageViewWave
setImage:[UIImage
imageNamed:@"record_animate_10.png"]];
}else
if (0.69<lowPassResults<=0.76) {

[self.imageViewWave
setImage:[UIImage
imageNamed:@"record_animate_11.png"]];
}else
if (0.76<lowPassResults<=0.83) {

[self.imageViewWave
setImage:[UIImage
imageNamed:@"record_animate_12.png"]];
}else
if (0.83<lowPassResults<=0.9) {

[self.imageViewWave
setImage:[UIImage
imageNamed:@"record_animate_13.png"]];
}else {

[self.imageViewWave
setImage:[UIImage
imageNamed:@"record_animate_14.png"]];
}
}

- (void) updateImage
{

[self.imageViewWave
setImage:[UIImage
imageNamed:@"record_animate_01.png"]];
}

//优化UI
- (void)didReceiveMemoryWarning {

[super
didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

if([self
isViewLoaded ] && self.view.window ==
nil){

self.view =
nil;
}
}

/*

#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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: