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

时间:2018-11-25 11:28:55

标签: ios swift avaudioplayer avaudiorecorder

我正在尝试编写代码以录制2秒钟的音频,并在录制完成后自动播放。这段代码没有任何错误,但是它似乎根本没有记录,而是直接跳到if循环中并显示“ recording success ...”,并且不会播放任何内容。

@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,并且在实现基于“开始”,“停止”按钮的Audio Recorder方面也没有问题,但是在这里似乎record(forDurartion:)函数不起作用。

预先感谢

1 个答案:

答案 0 :(得分:1)

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

@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...")
        }