//导入系统库 AVFoundation
var _recorder :AVAudioRecorder?
var _player: AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
//设置录制文件的访问路径
let cachePathArray = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let cachePath = cachePathArray[0] as! String
let realPath = cachePath.stringByAppendingPathComponent("recorder.wav")
print("路径:\(realPath)")
let url = NSURL(fileURLWithPath: realPath)
//设置录音参数
let dict: Dictionary<String,AnyObject> = [
AVEncoderAudioQualityKey : AVAudioQuality.Min.rawValue, //录音质量
AVEncoderBitRateKey : 2 , //比特率
AVSampleRateKey : 44100] //采样率
var error: NSError? = nil
_recorder = AVAudioRecorder(URL: url, settings: dict, error: &error)
_recorder?.delegate = self
if error == nil {
//出错
}else {
_recorder?.prepareToRecord() //准备去录音
}
//初始化播放器
_player = AVAudioPlayer(contentsOfURL: url, error: nil)
_player?.delegate = self
}
//MARK: recorderDelegate 中断代理
func audioRecorderBeginInterruption(recorder: AVAudioRecorder!) {
_recorder?.pause()
}
func audioRecorderEndInterruption(recorder: AVAudioRecorder!) {
_recorder?.prepareToRecord()
_recorder?.record()
}
//MARK: playerDelegate 中断代理
func audioPlayerBeginInterruption(player: AVAudioPlayer!) {
_player?.pause()
}
func audioPlayerEndInterruption(player: AVAudioPlayer!) {
_player?.prepareToPlay()
_player?.play()
}