首页 > 解决方案 > Swift 4 - 覆盖 AVAudioRecorder 录音

问题描述

我正在使用 AvAudioRecorder 在我的 iOS 应用程序中进行录音。我可以进行初始录制,但我想给用户重新录制的选项。

我有这些定义:

var recordingSession: AVAudioSession!

var audioRecorder: AVAudioRecorder!

在我的 viewDidLoad 我有这个:

recordingSession = AVAudioSession.sharedInstance()

        do {

            try recordingSession.setCategory(AVAudioSessionCategoryPlayAndRecord)

            try recordingSession.setActive(true)

            recordingSession.requestRecordPermission() { result in

                DispatchQueue.main.async {

                    if(result == true)
                    {

                    }
                    else
                    {

                    }

                }

            }

        }
        catch
        {

        }

然后我有我的录制按钮:

@IBAction func recordButtonPressed(_ sender: Any) {

        if audioRecorder == nil {
            startRecording()
        } else {
            finishRecording(success: true)
        }

    }

这是我开始录制和完成录制的方法:

func startRecording() {

        audioFilename = getDocumentsDirectory().appendingPathComponent("recording.m4a")

        let settings = [
            AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
            AVSampleRateKey: 12000,
            AVNumberOfChannelsKey: 1,
            AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
        ]

        do {

            audioRecorder = try AVAudioRecorder(url: audioFilename, settings: settings)
            audioRecorder.delegate = self
            audioRecorder.record()

            recordButton.setTitle("Tap to Stop", for: .normal)

        } catch {

            finishRecording(success: false)

        }
    }

    func finishRecording(success: Bool) {

        audioRecorder.stop()
        audioRecorder = nil

        if success {
            recordButton.setTitle("Tap to Re-record", for: .normal)

            audioSlider.isHidden = false
            playButton.isHidden = false
            uploadButton.isHidden = false

            do {

                try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
                try AVAudioSession.sharedInstance().setActive(true)

                self.audioPlayer = try AVAudioPlayer(contentsOf: audioFilename)
                self.audioPlayer?.prepareToPlay()

            }catch{

            }


        } else {
            recordButton.setTitle("Tap to Record", for: .normal)
        }
    }

问题是我尝试重新录制的任何内容都没有。录制完成后,我尝试将 audioRecorder 设置为 nil,但这根本没有帮助。

标签: iosswift

解决方案


推荐阅读