AVAudioPlayer与AVAudioRecorder(录音及播放及定时器计时)

这里写图片描述

在iOS10上,如果没有使用者允许的话,不能存取麦克风,所以需要在Info.plist中添加NSMicrophoneUsageDescription的key,并告知你的使用者为何你的app需要麦克风

import UIKit
import AVFoundation

class RecordProController: UIViewController {
    private var timer:Timer?
    private var elapsedTimeInSecond:Int = 0
    var audioRecorder:AVAudioRecorder!
    var audioPlayer:AVAudioPlayer?
    @IBOutlet private var stopButton: UIButton!
    @IBOutlet private var playButton: UIButton!
    @IBOutlet private var recordButton: UIButton!
    @IBOutlet private var timeLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        configure()
    }

    private func configure(){
        stopButton.isEnabled = false
        playButton.isEnabled = false
        guard let directoryURL = FileManager.default.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).first else {
            let alertMessage = UIAlertController(title: "Error", message: "Failed to get the document directory for recording the audio.please try again later", preferredStyle: .alert)
            alertMessage.addAction(UIAlertAction(title: "O,", style: .default, handler: nil))
            present(alertMessage, animated: true, completion: nil)
            return
        }

        // 设定预设
        let audioFileURL = directoryURL.appendingPathComponent("MyAudioMemo.m4a")
        // 设定session
        let audioSession = AVAudioSession.sharedInstance()
        do {
            try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, with: AVAudioSessionCategoryOptions.defaultToSpeaker)

            // 下面这个是错误的,写出来之后会抛出throw catch Error Domain=NSOSStatusErrorDomain Code=-50 "(null)"
//             try audioSession.setCategory(AVAudioSessionCategoryRecord, with: AVAudioSessionCategoryOptions.defaultToSpeaker)
            // 定义录音器
            let recorderSetting : [String:Any] = [
                AVFormatIDKey:Int(kAudioFormatMPEG4AAC),
                // 取样率
                AVSampleRateKey:44100.0,
                // 频道数
                AVNumberOfChannelsKey:2,
                // 声音质量
                AVEncoderAudioQualityKey:AVAudioQuality.high.rawValue
            ]
            // 初始化准备录音
            audioRecorder = try AVAudioRecorder(url: audioFileURL, settings:recorderSetting)
            audioRecorder.delegate = self
            audioRecorder.isMeteringEnabled = true
            audioRecorder.prepareToRecord()

        } catch  {
            print(error)
        }
    }

    func startTimer() {
        // 每隔1秒启动一次
        timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { (time) in
            self.elapsedTimeInSecond += 1
            self.updateTimeLabel()
        })
    }

    func pauseTimer()  {
        timer?.invalidate()
    }

    func resetTimer(){
        timer?.invalidate()
        elapsedTimeInSecond = 0
        updateTimeLabel()
    }

    func updateTimeLabel(){
        let seconds = elapsedTimeInSecond % 60
        let minutes = (elapsedTimeInSecond / 60) % 60
        timeLabel.text = String(format: "%02d:%02d", minutes,seconds)

    }
    // MARK: - Action methods

    @IBAction func stop(sender: UIButton) {

        recordButton.setImage(UIImage(named: "Record"), for: .normal)
        recordButton.isEnabled = true
        stopButton.isEnabled = false
        playButton.isEnabled = true
        // 停止录音
        audioRecorder.stop()
        resetTimer()
        let audioSession = AVAudioSession.sharedInstance()
        do {
            // 停止录音
            try audioSession.setActive(false)
        } catch  {

        }
    }

    @IBAction func play(sender: UIButton) {
        if !audioRecorder.isRecording{
            guard let player = try? AVAudioPlayer(contentsOf: audioRecorder.url)else{
                print("failed to initialize AVAudioPlayer")
                return
            }
            audioPlayer = player
            audioPlayer?.delegate = self

            audioPlayer?.play()
            startTimer()
      }

    }
    @IBAction func record(sender: UIButton) {
        // 录音之前停止播放
        if let myPlayer = audioPlayer,myPlayer.isPlaying {
            myPlayer.stop()
        }
        if !audioRecorder.isRecording {
            let audioSession = AVAudioSession.sharedInstance()
            do{
                // 启动录音
               try audioSession.setActive(true)
                // 开始录音
                audioRecorder.record()
                startTimer()
                // 变更为暂停图片
                recordButton.setImage(UIImage(named: "Pause"), for: UIControlState.normal)
            }catch{
                print(error)
            }
        }else{
            // 暂停录制
            audioRecorder.pause()
            pauseTimer()
            // 变更为录制图片
            recordButton.setImage(UIImage(named: "Record"), for: UIControlState.normal)
        }
        stopButton.isEnabled = true
        playButton.isEnabled = false
    }

}


extension RecordProController:AVAudioRecorderDelegate{
    func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
        if flag {
            let alertMessage = UIAlertController(title: "finished record", message: "succcessfully recorded the audio", preferredStyle: .alert)
            alertMessage.addAction(UIAlertAction(title: "ok", style: .default, handler: nil))
            present(alertMessage, animated: true, completion: nil)
        }
    }
}

extension RecordProController:AVAudioPlayerDelegate{
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        playButton.isSelected = false
        resetTimer()
        let alertMessage = UIAlertController(title: "finished player", message: "succcessfully recorded the audio", preferredStyle: .alert)
        alertMessage.addAction(UIAlertAction(title: "ok", style: .default, handler: nil))
        present(alertMessage, animated: true, completion: nil)
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值