如何使用 AV Audio 录制一段特定时间的音频

How to record audio for a certain duration using AV Audio

我正在尝试编写一个代码来录制音频 2 秒,并在完成录制后自动播放。这段代码没有错误,但是好像根本没有记录,直接跳到if循环里面打印"recording successful...",不播放任何东西。

@IBAction func buttonPressedDAF(_ sender: UIButton) {

    print("starting DAF...")


    let filename = getDirectory().appendingPathComponent("\(fileNameString)")

    let settings = [AVFormatIDKey: Int(kAudioFormatAppleLossless),
                    AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue,
                    AVEncoderBitRateKey: 320000,
                    AVNumberOfChannelsKey: 1,
                    AVSampleRateKey: 12000.0] as [String : Any]

    do{

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


        if(audioRecorder.record(forDuration: 2 ))

        {
            print("recording succesfull...")
            audioRecorder.stop()
            audioRecorder = nil
            playRecording()
        }


    }
    catch {
        print ("failed...")
    }

我之前已经使用过 AV Audio,并且在实现基于开始、停止按钮的录音机方面没有问题,但是在这里,record(forDurartion:) 功能似乎无法正常工作。

提前致谢

如果没有完成块,你可以使用我下面的代码来延迟调用停止记录代码:)

@IBAction func buttonPressedDAF(_ sender: UIButton) {

        print("starting DAF...")


        let filename = getDirectory().appendingPathComponent("\(fileNameString)")

        let settings = [AVFormatIDKey: Int(kAudioFormatAppleLossless),
                        AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue,
                        AVEncoderBitRateKey: 320000,
                        AVNumberOfChannelsKey: 1,
                        AVSampleRateKey: 12000.0] as [String : Any]

        do{

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


            if(audioRecorder.record(forDuration: 2 ))

            {
                // .now() + number of seconds
                DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
                    print("recording succesfull...")
                    self.audioRecorder.stop()
                    self.audioRecorder = nil
                    self.playRecording()
                }
            }


        }
        catch {
            print ("failed...")
        }