swift 录音demo

以下是用swift写的一个录音demo, 把声音录制保存到沙盒里, 并获得声音的分贝值大小. (亲测可用!)

importUIKit

importAVFoundation

classViewController:UIViewController{

//定义录音器

varrecord:AVAudioRecorder?

//定义定时器,用来获得声音的分贝大小,显示到界面

vartimer:CADisplayLink?

overridefuncviewDidLoad(){

super.viewDidLoad()

}

}

extensionViewController{

@IBActionfuncbeginRecord(sender:UIButton){

//1.获取录制文件的存放的路径

letfilePath=NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)[0]

letfileName=filePath.stringByAppendingString("/woailo.wav")

guardletfileURL=NSURL(string:fileName)else{

return

}

//2.创建录制音频的对象44100-->8000

guardletrecord=try?AVAudioRecorder(URL:fileURL,settings:[AVSampleRateKey:80000])else{

return

}

self.record=record

//3.开始录制

record.record()

print(fileURL)

print(fileName)

//4.测试声音的大小

record.meteringEnabled=true

//4.开启定时器

timer=CADisplayLink(target:self,selector:#selector(getVolumePower))

timer?.addToRunLoop(NSRunLoop.mainRunLoop(),forMode:NSRunLoopCommonModes)

}

@objcprivatefuncgetVolumePower(){

//updateMeters要和averagePowerForChannel配合使用

record?.updateMeters()

letpowerLeval=record?.averagePowerForChannel(0)

print(powerLeval)

}

@IBActionfuncstopRecord(sender:UIButton){

record?.stop()

timer?.invalidate()

timer=nil

}

}

你可能感兴趣的:(swift 录音demo)