录音播放

效果如图

主要代码如下

#import "ViewController.h"#import#import "lame.h"

//用宏来定义需要用到的变量 运算符

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

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

#define NAVBAR_HEIGHT 40

#define TITLE_X (SCREEN_WIDTH/2-SCREEN_WIDTH/10)

#define TITLE_Y (1.5*NAVBAR_HEIGHT)

#define TITLE_WIDTH (SCREEN_WIDTH/5)

#define TITLE_HEIGHT NAVBAR_HEIGHT

#define RECORDBAR_X (SCREEN_WIDTH/2-SCREEN_WIDTH/4)

#define RECORDBAR_Y (TITLE_Y+TITLE_HEIGHT+NAVBAR_HEIGHT/2)

#define RECORDBAR_WIDTH (SCREEN_WIDTH/2)

#define TIME_X (SCREEN_WIDTH/2-SCREEN_WIDTH/8)

#define TIME_Y (RECORDBAR_Y+NAVBAR_HEIGHT)

#define TIME_WIDTH (SCREEN_WIDTH/4)

#define TIME_HEIGHT NAVBAR_HEIGHT

#define RECORDBUTTON_X (SCREEN_WIDTH/2-SCREEN_WIDTH/6)

#define RECORDBUTTON_Y (TIME_Y+TIME_HEIGHT+NAVBAR_HEIGHT/2)

#define RECORDBUTTON_WIDTH (SCREEN_WIDTH/3)

#define RECORDBUTTON_HEIGHT RECORDBUTTON_WIDTH

#define PLAYBUTTON_X (SCREEN_WIDTH/2-SCREEN_WIDTH/8)

#define PLAYBUTTON_Y (TIME_Y+2*TIME_HEIGHT)

#define PLAYBUTTON_WIDTH SCREEN_WIDTH/4

#define PLAYBUTTON_HEIGHT PLAYBUTTON_WIDTH

#define RECORE_BUTTON_TAG 1010

#define NEW_PLAY_BUTTON_TAG 1011

#define PAUSE_PLAY_BUTTON_TAG 1012

#define FINISH_BUTTON_TAG 1013

#define RECORDAGAIN_BUTTON_TAG 1014

#define PAUSE_BUTTON_TAG 1015

@interface ViewController ()

@end

@implementation ViewController

{

UILabel* recordTitleLabel; //记录标题标签

UISlider* progressView;    //进度条

UILabel* timeLabel;          //时间表

UIButton* recordButton;        //录音按钮

UILabel* recordLabel;

NSTimer* timer;

int recordTime;    //录音时间

int playTime;      //播放时间

int playDuration;    //播放持续时间

int second;

int minute;

UIButton* playButton;      //播放按钮

UIButton* finishButton;      //完成按钮

UIButton* pauseButton;      //暂停按钮

UIButton* recordAgainButton;  //重新录制按钮

UILabel* playLabel;

UILabel* finishLabel;

UILabel* pauseLabel;

UILabel* recordAgainLabel;

AVAudioRecorder *audioRecorder;

AVAudioPlayer *audioPlayer;

AVAudioSession * audioSession;

NSURL* recordUrl;

NSURL* mp3FilePath;

NSURL* audioFileSavePath;

}

- (void)viewDidLoad {

[self initializeUI];

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

}

- (void)initializeUI {

playButton = [[UIButton alloc] initWithFrame:CGRectMake(PLAYBUTTON_X, PLAYBUTTON_Y, PLAYBUTTON_WIDTH, PLAYBUTTON_HEIGHT)];

[playButton setImage:[UIImage imageNamed:@"play_button.png"] forState:UIControlStateNormal];

playButton.tag = NEW_PLAY_BUTTON_TAG;

[playButton addTarget:self action:@selector(clickOnButton:) forControlEvents:UIControlEventTouchUpInside];

playLabel = [[UILabel alloc] initWithFrame:CGRectMake(PLAYBUTTON_X, PLAYBUTTON_Y+PLAYBUTTON_HEIGHT, PLAYBUTTON_WIDTH, NAVBAR_HEIGHT)];

[playLabel setText:@"播放"];

[playLabel setTextAlignment:NSTextAlignmentCenter];

pauseButton = [[UIButton alloc] initWithFrame:CGRectMake(PLAYBUTTON_X, PLAYBUTTON_Y, PLAYBUTTON_WIDTH, PLAYBUTTON_HEIGHT)];

[pauseButton setImage:[UIImage imageNamed:@"pause_button.png"] forState:UIControlStateNormal];

pauseButton.tag = PAUSE_BUTTON_TAG;

[pauseButton addTarget:self action:@selector(clickOnButton:) forControlEvents:UIControlEventTouchUpInside];

pauseLabel = [[UILabel alloc] initWithFrame:CGRectMake(PLAYBUTTON_X, PLAYBUTTON_Y+PLAYBUTTON_HEIGHT, PLAYBUTTON_WIDTH, NAVBAR_HEIGHT)];

[pauseLabel setText:@"暂停"];

[pauseLabel setTextAlignment:NSTextAlignmentCenter];

finishButton = [[UIButton alloc] initWithFrame:CGRectMake(PLAYBUTTON_X-PLAYBUTTON_WIDTH-10, PLAYBUTTON_Y, PLAYBUTTON_WIDTH, PLAYBUTTON_HEIGHT)];

[finishButton setImage:[UIImage imageNamed:@"finish_button.png"] forState:UIControlStateNormal];

finishButton.tag = FINISH_BUTTON_TAG;

[finishButton addTarget:self action:@selector(clickOnButton:) forControlEvents:UIControlEventTouchUpInside];

finishLabel = [[UILabel alloc] initWithFrame:CGRectMake(PLAYBUTTON_X-PLAYBUTTON_WIDTH-10, PLAYBUTTON_Y+PLAYBUTTON_HEIGHT, PLAYBUTTON_WIDTH, NAVBAR_HEIGHT)];

[finishLabel setText:@"完成"];

[finishLabel setTextAlignment:NSTextAlignmentCenter];

recordAgainButton = [[UIButton alloc] initWithFrame:CGRectMake(PLAYBUTTON_X+PLAYBUTTON_WIDTH+10, PLAYBUTTON_Y, PLAYBUTTON_WIDTH, PLAYBUTTON_HEIGHT)];

[recordAgainButton setImage:[UIImage imageNamed:@"record_again_button.png"] forState:UIControlStateNormal];

recordAgainButton.tag = RECORDAGAIN_BUTTON_TAG;

[recordAgainButton addTarget:self action:@selector(clickOnButton:) forControlEvents:UIControlEventTouchUpInside];

recordAgainLabel = [[UILabel alloc] initWithFrame:CGRectMake(PLAYBUTTON_X+PLAYBUTTON_WIDTH+10, PLAYBUTTON_Y+PLAYBUTTON_HEIGHT, PLAYBUTTON_WIDTH, NAVBAR_HEIGHT)];

[recordAgainLabel setText:@"重新录制"];

[recordAgainLabel setTextAlignment:NSTextAlignmentCenter];

recordTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(TITLE_X, TITLE_Y, SCREEN_WIDTH, TITLE_HEIGHT)];

[recordTitleLabel setText:@"录制语音"];

progressView = [[UISlider alloc] initWithFrame:CGRectMake(RECORDBAR_X, RECORDBAR_Y, RECORDBAR_WIDTH, 20)];

[progressView setThumbImage:[UIImage imageNamed:@"one.png"] forState:UIControlStateNormal];

progressView.value = 0;

progressView.userInteractionEnabled = NO;

timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(TIME_X, TIME_Y, TIME_WIDTH, TIME_HEIGHT)];

[timeLabel setText:@"00:00"];

[timeLabel setFont:[UIFont systemFontOfSize:32]];

[timeLabel setTextColor:[UIColor blackColor]];

recordButton = [[UIButton alloc] initWithFrame:CGRectMake(RECORDBUTTON_X, RECORDBUTTON_Y, RECORDBUTTON_WIDTH, RECORDBUTTON_HEIGHT)];

recordButton.tag = RECORE_BUTTON_TAG;

[recordButton addTarget:self action:@selector(clickOnButton:) forControlEvents:UIControlEventTouchUpInside];

[recordButton setImage:[UIImage imageNamed:@"record_button.png"] forState:UIControlStateNormal];

recordLabel = [[UILabel alloc] initWithFrame:CGRectMake(RECORDBUTTON_X, RECORDBUTTON_Y+RECORDBUTTON_HEIGHT, RECORDBUTTON_WIDTH, NAVBAR_HEIGHT/2)];

[recordLabel setText:@"点击开始"];

[recordLabel setTextAlignment:NSTextAlignmentCenter];

//录音设置

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

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

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

//设置录音采样率(Hz) 如:AVSampleRateKey==8000/44100/96000(影响音频的质量), 采样率必须要设为11025才能使转化成mp3格式后不会失真

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

//录音通道数  1 或 2 ,要转换成mp3格式必须为双通道

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

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

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

//录音的质量

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

//存储录音文件

recordUrl = [NSURL URLWithString:[NSTemporaryDirectory() stringByAppendingString:@"selfRecord.caf"]];

//初始化

audioRecorder = [[AVAudioRecorder alloc] initWithURL:recordUrl settings:recordSetting error:nil];

//开启音量检测

audioRecorder.meteringEnabled = YES;

audioRecorder.delegate = self;

[self.view addSubview:recordTitleLabel];

[self.view addSubview:progressView];

[self.view addSubview:timeLabel];

[self.view addSubview:recordButton];

[self.view addSubview:recordLabel];

}

- (void)transformCAFToMP3 {

mp3FilePath = [NSURL URLWithString:[NSTemporaryDirectory() stringByAppendingString:@"myselfRecord.mp3"]];

@try {

int read, write;

FILE *pcm = fopen([[recordUrl absoluteString] cStringUsingEncoding:1], "rb");  //source 被转换的音频文件位置

fseek(pcm, 4*1024, SEEK_CUR);                                                  //skip file header

FILE *mp3 = fopen([[mp3FilePath absoluteString] cStringUsingEncoding:1], "wb"); //output 输出生成的Mp3文件位置

const int PCM_SIZE = 8192;

const int MP3_SIZE = 8192;

short int pcm_buffer[PCM_SIZE*2];

unsigned char mp3_buffer[MP3_SIZE];

lame_t lame = lame_init();

lame_set_in_samplerate(lame, 11025.0);

lame_set_VBR(lame, vbr_default);

lame_init_params(lame);

do {

read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);

if (read == 0)

write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);

else

write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);

fwrite(mp3_buffer, write, 1, mp3);

} while (read != 0);

lame_close(lame);

fclose(mp3);

fclose(pcm);

}

@catch (NSException *exception) {

NSLog(@"%@",[exception description]);

}

@finally {

audioFileSavePath = mp3FilePath;

NSLog(@"MP3生成成功: %@",audioFileSavePath);

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"mp3转化成功!" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];

[alert show];

}

}

- (void)clickOnButton:(UIButton*)sender {

audioSession = [AVAudioSession sharedInstance];//得到AVAudioSession单例对象

switch (sender.tag) {

case RECORE_BUTTON_TAG:{

if (![audioRecorder isRecording]) {

[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];//设置类别,表示该应用同时支持播放和录音

[audioSession setActive:YES error:nil];//启动音频会话管理,此时会阻断后台音乐的播放.

[audioRecorder prepareToRecord];

[audioRecorder peakPowerForChannel:0.0];

[audioRecorder record];

recordTime = 0;

[self recordTimeStart];

[recordButton setImage:[UIImage imageNamed:@"recording_button.png"] forState:UIControlStateNormal];

[recordLabel setText:@"点击结束"];

}

else{

[audioRecorder stop];                          //录音停止

[audioSession setActive:NO error:nil];        //一定要在录音停止以后再关闭音频会话管理(否则会报错),此时会延续后台音乐播放

[timer invalidate];                            //timer失效

[timeLabel setText:@"00:00"];                  //时间显示复位

[progressView setValue:0 animated:YES];        //进度条复位

[recordButton removeFromSuperview];

[recordLabel removeFromSuperview];

[self.view addSubview:playButton];

[self.view addSubview:finishButton];

[self.view addSubview:recordAgainButton];

[self.view addSubview:playLabel];

[self.view addSubview:finishLabel];

[self.view addSubview:recordAgainLabel];

}

}

break;

case NEW_PLAY_BUTTON_TAG:{

[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];

[audioSession setActive:YES error:nil];

if (mp3FilePath != nil) {

audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:mp3FilePath error:nil];

}

else if (recordUrl != nil){

audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:recordUrl error:nil];

}

[audioPlayer prepareToPlay];

audioPlayer.volume = 1;

[audioPlayer play];

[playButton removeFromSuperview];

[playLabel removeFromSuperview];

[self.view addSubview:pauseButton];

[self.view addSubview:pauseLabel];

playDuration = (int)audioPlayer.duration;

NSLog(@"音频时长为:%i",playDuration);

playTime = 0;

[self audioPlayTimeStart];

}

break;

case PAUSE_PLAY_BUTTON_TAG:{

[audioSession setActive:YES error:nil];

[audioPlayer play];

[playButton removeFromSuperview];

[playLabel removeFromSuperview];

[self.view addSubview:pauseButton];

[self.view addSubview:pauseLabel];

}

break;

case PAUSE_BUTTON_TAG:{

[audioPlayer pause];

[audioSession setActive:NO error:nil];

playButton.tag = PAUSE_PLAY_BUTTON_TAG;

[pauseButton removeFromSuperview];

[pauseLabel removeFromSuperview];

[self.view addSubview:playButton];

[self.view addSubview:playLabel];

}

break;

case FINISH_BUTTON_TAG:{

[self transformCAFToMP3];

}

break;

case RECORDAGAIN_BUTTON_TAG:{

[audioPlayer stop];

[audioRecorder stop];

[audioSession setActive:NO error:nil];

[timer invalidate];

progressView.value = 0;

[timeLabel setText:@"00:00"];

recordTime = 0;

playTime = 0;

[playButton removeFromSuperview];

[pauseButton removeFromSuperview];

[finishButton removeFromSuperview];

[recordAgainButton removeFromSuperview];

[playLabel removeFromSuperview];

[pauseLabel removeFromSuperview];

[finishLabel removeFromSuperview];

[recordAgainLabel removeFromSuperview];

[self.view addSubview:recordButton];

[self.view addSubview:recordLabel];

[recordButton setImage:[UIImage imageNamed:@"record_button.png"] forState:UIControlStateNormal];

[recordLabel setText:@"点击开始"];

}

break;

default:

break;

}

}

- (void)recordTimeStart {

timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(recordTimeTick) userInfo:nil repeats:YES];

}

- (void)recordTimeTick {

recordTime += 1;

[progressView setValue:(float)recordTime/30.0 animated:YES];

if (recordTime == 30) {

recordTime = 0;

[audioRecorder stop];

[[AVAudioSession sharedInstance] setActive:NO error:nil];

[timer invalidate];

[timeLabel setText:@"00:00"];

[progressView setValue:0.0 animated:YES];

[recordButton removeFromSuperview];

[recordLabel removeFromSuperview];

[self.view addSubview:playButton];

[self.view addSubview:finishButton];

[self.view addSubview:recordAgainButton];

[self.view addSubview:playLabel];

[self.view addSubview:finishLabel];

[self.view addSubview:recordAgainLabel];

return;

}

[self updateAudioRecordTime];

}

- (void)updateAudioRecordTime {

minute = recordTime/60.0;

second = recordTime-minute*60;

[timeLabel setText:[NSString stringWithFormat:@"%02d:%02d",minute,second]];

}

- (void)audioPlayTimeStart {

timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(playTimeTick) userInfo:nil repeats:YES];

}

- (void)playTimeTick {

if (playDuration == playTime) {

playTime = 0;

[audioPlayer stop];

[[AVAudioSession sharedInstance] setActive:NO error:nil];

[pauseButton removeFromSuperview];

[pauseLabel removeFromSuperview];

[self.view addSubview:playButton];

[self.view addSubview:playLabel];

playButton.tag = NEW_PLAY_BUTTON_TAG;

[timeLabel setText:@"00:00"];

[timer invalidate];

progressView.value = 0;

return;

}

if (![audioPlayer isPlaying]) {

return;

}

playTime += 1;

[progressView setValue:(float)playTime/(float)playDuration animated:YES];

[self updateAudioPlayTime];

}

- (void)updateAudioPlayTime {

minute = playTime/60.0;

second = playTime-minute*60;

[timeLabel setText:[NSString stringWithFormat:@"%02d:%02d",minute,second]];

}

//AVAudioRecorderDelegate方法

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {

[audioSession setActive:NO error:nil];

playTime = 0;

[pauseButton removeFromSuperview];

[pauseLabel removeFromSuperview];

[self.view addSubview:playButton];

[self.view addSubview:playLabel];

playButton.tag = NEW_PLAY_BUTTON_TAG;

[timeLabel setText:@"00:00"];

[timer invalidate];

progressView.value = 0;

}

- (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

@end

注意要开启麦克风权限,如果模拟器可以用真机却不可以,将Enable Bitcode 关闭就可以了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,324评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,303评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,192评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,555评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,569评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,566评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,927评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,583评论 0 257
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,827评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,590评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,669评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,365评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,941评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,928评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,159评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,880评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,399评论 2 342

推荐阅读更多精彩内容