IOS 录音与播放

来源:互联网 发布:指纹考勤机数据修改 编辑:程序博客网 时间:2024/05/16 18:15

三个按钮分别为 录制,停止,播放

import UIKitimport AVFoundationclass ViewController: UIViewController {    var avRec:AVAudioRecorder!    var audioFileUrl:NSURL!    var avPlayer:AVAudioPlayer!    var recordSetting:[String : AnyObject] = ["":""] //nil不可用时    @IBAction func startRec(sender: AnyObject) {        print("start rec")        avRec.record()//开始录制    }    @IBAction func stopRec(sender: AnyObject) {        print("stop rec")        avRec.stop()//停止录制    }    @IBAction func playRec(sender: AnyObject) {        print("play rec")        //创建avPlayer        avPlayer = try? AVAudioPlayer(contentsOfURL: audioFileUrl)        avPlayer.prepareToPlay()//准备播放        avPlayer.play()//播放录制    }    override func viewDidLoad() {        super.viewDidLoad()        // Do any additional setup after loading the view, typically from a nib.        //创建一个URL        //DocumentDirectory文档目录        //inDomains所在的域        //(NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.AllDomainsMask)[0] as NSURL).        //找到文档名字        //URLByAppendingPathComponent创建文件        audioFileUrl = (NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.AllDomainsMask)[0] as NSURL).URLByAppendingPathComponent("rec")        avRec = try? AVAudioRecorder.init(URL: audioFileUrl!, settings: recordSetting)      //URL存放录音文件的地址        avRec.prepareToRecord()//开始准备路径    }    override func didReceiveMemoryWarning() {        super.didReceiveMemoryWarning()        // Dispose of any resources that can be recreated.    }}
0 0