import UIKit
import AVFoundation
class ViewController : UIViewController {
var recorder: AVAudioRecorder ? //录音器
var player: AVAudioPlayer ? //播放器
var recorderSeetingsDic:[ NSObject : AnyObject ]? //录音器设置参数数组
var volumeTimer: NSTimer ! //定时器线程,循环监测录音的音量大小
var aacPath: String ? //录音存储路径
@IBOutlet weak var volumLab: UILabel ! //显示录音音量
override func viewDidLoad() {
super .viewDidLoad()
//初始化录音器
let session: AVAudioSession = AVAudioSession .sharedInstance()
//用于获取失败原因
var error: NSError ?
//设置录音类型
session.setCategory( AVAudioSessionCategoryPlayAndRecord , error: &error)
//设置支持后台
session.setActive( true , error: &error)
//获取Document目录
let docDir = NSSearchPathForDirectoriesInDomains (. DocumentDirectory ,
. UserDomainMask , true )[0] as ! String
//组合录音文件路径
aacPath = docDir + "/play.aac"
//初始化字典并添加设置参数
recorderSeetingsDic = Dictionary ()
recorderSeetingsDic!.updateValue( NSNumber (long: kAudioFormatMPEG4AAC), forKey: AVFormatIDKey )
//录音器每秒采集的录音样本数
recorderSeetingsDic!.updateValue( NSNumber (long: 1000), forKey: AVSampleRateKey )
//录音的声道数,立体声为双声道
recorderSeetingsDic!.updateValue( NSNumber (long: 2), forKey: AVNumberOfChannelsKey )
//采样位数
recorderSeetingsDic!.updateValue( NSNumber (long: 8), forKey: AVLinearPCMBitDepthKey )
//大端还是小段,是内存的组织方式
recorderSeetingsDic!.updateValue( NSNumber (bool: false ), forKey: AVLinearPCMIsBigEndianKey )
//采样信号是整数还是浮点
recorderSeetingsDic!.updateValue( NSNumber (bool: false ), forKey: AVLinearPCMIsFloatKey )
}
override func didReceiveMemoryWarning() {
super .didReceiveMemoryWarning()
}
//按下录音
@IBAction func downAction(sender: AnyObject ) {
var error: NSError ?
//初始化录音器
recorder = AVAudioRecorder ( URL : NSURL (string: aacPath!),
settings: recorderSeetingsDic, error: &error)
if recorder != nil {
//开启仪表计数功能
recorder!.meteringEnabled = true
//准备录音
recorder!.prepareToRecord()
//开始录音
recorder!.record()
//启动定时器,定时更新录音音量
volumeTimer = NSTimer .scheduledTimerWithTimeInterval(0.1, target: self ,
selector: "levelTimer" , userInfo: nil , repeats: true )
}
}
//松开按钮,结束录音
@IBAction func upAction(sender: AnyObject ) {
//停止录音
recorder?.stop()
//录音器释放
recorder = nil
//暂停定时器
volumeTimer.invalidate()
volumeTimer = nil
volumLab.text = "录音音量:0"
}
//播放录制的声音
@IBAction func playAction(sender: AnyObject ) {
var error: NSError ?
//播放
player = AVAudioPlayer (contentsOfURL: NSURL (string: aacPath!), error: &error)
if player == nil {
print ( "播放失败:\(error?.description)" )
} else {
player?.play()
}
}
//定时检测录音音量
func levelTimer(){
recorder!.updateMeters() // 刷新音量数据
let averageV: Float = recorder!.averagePowerForChannel(0) //获取音量的平均值
let maxV: Float = recorder!.peakPowerForChannel(0) //获取音量最大值
let lowPassResult: Double = pow( Double (10), Double (0.05*maxV))
volumLab.text = "录音音量:\(lowPassResult)"
}
}
|