菜鸟教程小白 发表于 2022-12-12 23:47:45

ios - 静默 X 秒后停止录音


                                            <p><p>我正在实现以下教程:<a href="https://www.appcoda.com/siri-speech-framework/" rel="noreferrer noopener nofollow">Speech To Text</a> </p>

<p>我正在使用 AVAudioEngine 和 SFSpeechRecognizer 录制音频
实现语音到文本。此处教程使用以下方法将语音引导至文本
一个开始和停止录制的按钮。</p>

<p>当应用程序获得
允许。但是几秒钟后我找不到任何停止录制的方法
沉默。以下是我的代码:</p>

<pre><code>import UIKit
import Speech

public class ViewController: UIViewController, SFSpeechRecognizerDelegate {
// MARK: Properties

private let speechRecognizer = SFSpeechRecognizer(locale: Locale(identifier: &#34;en-US&#34;))!

private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest?

private var recognitionTask: SFSpeechRecognitionTask?

private let audioEngine = AVAudioEngine()

@IBOutlet var textView : UILabel!

@IBOutlet var recordButton : UIButton!


public override func viewDidLoad() {
    super.viewDidLoad()

    recordButton.isEnabled = false
}

override public func viewDidAppear(_ animated: Bool) {
    speechRecognizer.delegate = self

    SFSpeechRecognizer.requestAuthorization { authStatus in
      /*
         The callback may not be called on the main thread. Add an
         operation to the main queue to update the record button&#39;s state.
         */
      OperationQueue.main.addOperation {
            switch authStatus {
            case .authorized:
                self.recordButton.isEnabled = true
                try! self.startRecording()
                self.recordButton.setTitle(&#34;Stop recording&#34;, for: [])


            case .denied:
                self.recordButton.isEnabled = false
                self.recordButton.setTitle(
                  &#34;User denied access to speech recognition&#34;,
                  for: .disabled
                )

            case .restricted:
                self.recordButton.isEnabled = false
                self.recordButton.setTitle(
                  &#34;Speech recognition restricted on this device&#34;,
                  for: .disabled
                )

            case .notDetermined:
                self.recordButton.isEnabled = false
                self.recordButton.setTitle(
                  &#34;Speech recognition not yet authorized&#34;,
                  for: .disabled
                )
            }
      }
    }
}

@IBAction func recordButtonTapped() {
    if audioEngine.isRunning {
      audioEngine.stop()
      recognitionRequest?.endAudio()
      recordButton.isEnabled = false
      recordButton.setTitle(&#34;Start Recording&#34;, for: [])
    } else {
      try! startRecording()
      recordButton.setTitle(&#34;Stop recording&#34;, for: [])
    }
}

private func startRecording() throws {

    // Cancel the previous task if it&#39;s running.
    if let recognitionTask = recognitionTask {
      recognitionTask.cancel()
      self.recognitionTask = nil
    }

    let audioSession = AVAudioSession.sharedInstance()
    try audioSession.setCategory(AVAudioSessionCategoryRecord)
    try audioSession.setMode(AVAudioSessionModeMeasurement)
    try audioSession.setActive(true, with: .notifyOthersOnDeactivation)

    recognitionRequest = SFSpeechAudioBufferRecognitionRequest()

    guard let inputNode = audioEngine.inputNode else {
      fatalError(&#34;Audio engine has no input node&#34;)
    }
    guard let recognitionRequest = recognitionRequest else {
      fatalError(&#34;Unable to created a SFSpeechAudioBufferRecognitionRequest object&#34;)
    }

    // Configure request so that results are returned before audio
    // recording is finished
    recognitionRequest.shouldReportPartialResults = true

    // A recognition task represents a speech recognition session.
    // We keep a reference to the task so that it can be cancelled.
    recognitionTask = speechRecognizer.recognitionTask(
      with: recognitionRequest
    ) { result, error in
      var isFinal = false

      if let result = result {
            self.textView.text = result.bestTranscription.formattedString
            isFinal = result.isFinal
      }

      if error != nil || isFinal {
            self.audioEngine.stop()
            inputNode.removeTap(onBus: 0)

            self.recognitionRequest = nil
            self.recognitionTask = nil

            self.recordButton.isEnabled = true
      }
    }

    let recordingFormat = inputNode.outputFormat(forBus: 0)
    inputNode.installTap(
      onBus: 0,
      bufferSize: 1024,
      format: recordingFormat
    ) { (buffer: AVAudioPCMBuffer, when: AVAudioTime) in
      self.recognitionRequest?.append(buffer)
    }

    audioEngine.prepare()

    try audioEngine.start()

    textView.text = &#34;(Go ahead, I&#39;m listening)&#34;
}

// MARK: SFSpeechRecognizerDelegate

public func speechRecognizer(
    _ speechRecognizer: SFSpeechRecognizer,
    availabilityDidChange available: Bool
) {
    if available {
      recordButton.isEnabled = true
      recordButton.setTitle(&#34;Start Recording&#34;, for: [])
    } else {
      recordButton.isEnabled = false
      recordButton.setTitle(&#34;Recognition not available&#34;, for: .disabled)
    }
}

// MARK: Interface Builder actions


}
</code></pre>

<p>该应用程序运行良好。但我想实现在 X 秒静音时停止音频引擎。</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>也许使用具有指定间隔的计时器,并在每次获得语音输入时失效。</p>

<p>您创建了一个始终失效的计时器,并在用户说话时在其上创建了一个新计时器。当用户停止说话时,时间结束并结束</p>

<p>示例:</p>

<pre><code>class text {
var timer:Timer?
   func startRecording() { createTimer(4) }

   func whileRecording() { createTimer(1) }

   func createTimer(_ interval:Double) {
       timer?.invalidate()
       timer =   Timer.scheduledTimer(withTimeInterval: interval, repeats: false) { (_) in
         if self.audioEngine.isRunning {
               self.stopRecording()
         }
       }
   }

}
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 静默 X 秒后停止录音,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/41977314/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/41977314/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 静默 X 秒后停止录音