15.Swift 录制音频

15.Swift 录制音频

  • Swift 录制音频

我们知道,AVAudioPlayer可以播放音频。但是与之对应的AVAudioRecorder是可以录制音频的。

AVAudioRecorder构造方法
AVAudioRecorder.init(URL url: NSURL, settings: [String : AnyObject]) throws

创建文件,准备自动记录
AVAudioRecorder.prepareToRecord() -> Bool

开始记录
AVAudioRecorder.record() -> Bool

停止记录,并关闭文件
AVAudioRecorder.stop()

    var avRec:AVAudioRecorder!
    var avUrl:NSURL!
    var avPlayer:AVAudioPlayer!

    // 初始化AVAudioRecorder
    func initAVAudioRecorder(){
        self.avUrl = (NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.AllDomainsMask)[0] as NSURL).URLByAppendingPathComponent("record")
        NSLog("\(self.avUrl)");

        // 录音文件配置
        let recordSettings = [
            AVEncoderAudioQualityKey: AVAudioQuality.Max.rawValue,
            AVEncoderBitRateKey: 320000,
            AVNumberOfChannelsKey: 2,
            AVSampleRateKey: 44100.0
        ]
        do{
            // 实例化AVAudioRecorder
            try self.avRec = AVAudioRecorder(URL: avUrl, settings: recordSettings as! [String : AnyObject])
            // 创建文件,准备记录。会自动记录
            self.avRec.prepareToRecord()
        }catch let error as NSError{
            NSLog("\(error.localizedDescription)")
        }catch {
            NSLog("Other error")
        }
    }

    // 开始录音
    @IBAction func startRecord(sender: AnyObject) {
        NSLog("start")
        // 开始记录
        self.avRec.record()
    }
    // 结束录音
    @IBAction func stopRecord(sender: AnyObject) {
        NSLog("stop")
        // 停止记录,并关闭文件
        self.avRec.stop()
    }

    // 播放录音
    @IBAction func playRecord(sender: AnyObject) {
        NSLog("playRecord")
        do{
            try self.avPlayer = AVAudioPlayer(contentsOfURL: self.avUrl)
        }catch let error as NSError{
            NSLog("\(error.localizedDescription)")
        }catch {
            NSLog("Other error")
        }
        self.avPlayer.prepareToPlay()
        avPlayer.play()
    }

你可能感兴趣的:(String,url,swift)