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

标签 ios swift avaudioplayer avaudiorecorder

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

@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:) 函数似乎无法正常工作。

提前致谢

最佳答案

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

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

关于ios - 如何使用 AV Audio 录制一段特定时间的音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53466983/

相关文章:

ios - 当我在模拟器上运行我的应用程序时,它不会在模拟器设置和位置服务下显示我的应用程序

iOS:知道哪个 UITableView Cell 被点击了

ios - 寻找 iOS 风格的快进和快退按钮图像

ios - audioPlayer 错误 : The operation couldn’t be completed.(OSStatus 错误 2003334207。)

ios - 从 Cognito 向客户端发布身份验证自定义响应

iphone - 使用延迟创建一个返回的方法

ios - 我的应用在 App Store 上被拒绝了,但我不明白为什么

swift - Swift4 转换后 "' init ' is deprecated"警告

ios - 如何停止其他ViewController的AVAudioPlayer?

ios Autolayout - 在图像上对齐文本