實現(xiàn)思路:
- 在故事板中定義兩個按鈕,一個"按下錄制"按鈕,和"播放"按鈕,"按下錄制"按鈕綁定兩個方法:錄音方法和結(jié)束錄音方法,"播放"按鈕綁定播放的方法
2 定義一個AVAudioRecorder(全局的),和一個AVAudioPlayer(全局),并且定義一個全局的NSURL(播放也需要沙盒路徑)
3 在錄音方法中定義它的沙盒路徑,并刪除之前的錄音,再初始化AVAudioRecorder變量 并準備錄制和錄制.
4 當松開按下時,調(diào)用結(jié)束錄音方法,調(diào)用錄音停止方法,并賦值為nil
5 在播放方法中,初始化AVAudioPlayer變量,并準備播放和播放音頻
故事板中的繪制:
音頻錄制和播放
實現(xiàn)代碼:
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()
{
AVAudioRecorder *recorder;//錄音對象
AVAudioPlayer *player;//播放對象
NSURL *fileUrl;//文件路徑
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
//按下錄音
- (IBAction)recoder:(id)sender {
//(1)url
NSString *urlStr = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/recoder.aac"];
//刪除之前的錄音
[[NSFileManager defaultManager]removeItemAtPath:urlStr error:nil];
fileUrl = [NSURL fileURLWithPath:urlStr];
//(2)設(shè)置錄音的音頻參數(shù)
/*
1 ID號:acc
2 采樣率(HZ):每秒從連續(xù)的信號中提取并組成離散信號的采樣個數(shù)
3 通道的個數(shù):(1 單聲道 2 立體聲)
4 采樣位數(shù)(8 16 24 32) 衡量聲音波動變化的參數(shù)
5 大端或者小端 (內(nèi)存的組織方式)
6 采集信號是整數(shù)還是浮點數(shù)
7 音頻編碼質(zhì)量
*/
NSDictionary *info = @{
AVFormatIDKey:[NSNumber numberWithInt:kAudioFormatMPEG4AAC],//音頻格式
AVSampleRateKey:@1000,//采樣率
AVNumberOfChannelsKey:@2,//聲道數(shù)
AVLinearPCMBitDepthKey:@8,//采樣位數(shù)
AVLinearPCMIsBigEndianKey:@NO,
AVLinearPCMIsFloatKey:@NO,
AVEncoderAudioQualityKey:[NSNumber numberWithInt:AVAudioQualityMedium],
};
/*
url:錄音文件保存的路徑
settings: 錄音的設(shè)置
error:錯誤
*/
recorder = [[AVAudioRecorder alloc]initWithURL:fileUrl settings:info error:nil];
[recorder prepareToRecord];
[recorder record];
}
//抬手結(jié)束錄音
- (IBAction)stopRecoder:(id)sender {
[recorder stop];
//手動釋放
recorder =nil;
}
//播放錄音
- (IBAction)playRecoder:(id)sender {
//多次播放的時候
player = nil;
player = [[AVAudioPlayer alloc]initWithContentsOfURL:fileUrl error:nil];
if (player) {
[player prepareToPlay];
[player play];
}
}
@end