ios - 我们如何在 swift 4 和 IOS 11 中更改语音识别语言?

标签 ios swift speech-recognition speech

我正在尝试使用 UISegmentedControl 更改 UI 中的语言,我想将不同的实例作为 ViewControler 类的属性,例如

    private let speechRecognizer_en = SFSpeechRecognizer(locale: Locale.init(identifier: "en-US"))  //1

    private let speechRecognizer_fr = SFSpeechRecognizer(locale: Locale.init(identifier: "fr-BE"))  //1

这是一种方式,但肯定不是最好的方式,我想知道你们能不能给我更好的主意我该怎么做?

这是应用程序源代码,我们输入了用户用英语说的内容,但我们想为用户提供更改语言的选项:

import UIKit
import Speech

class ViewController: UIViewController {

@IBOutlet weak var segView: UISegmentedControl!
@IBOutlet weak var startStopBtn: UIButton!
@IBOutlet weak var textView: UITextView!

private Let speechRecognizer = SFSpeechRecognizer(locale: Locale.init(identifier: "en-US"))  //1
private Let recognitionRequest: SFSpeechAudioBufferRecognitionRequest?
private Let recognitionTask: SFSpeechRecognitionTask?
private Let audioEngine = AVAudioEngine()

override func viewDidLoad() {
    super.viewDidLoad()

    startStopBtn.isEnabled = false  //2

    speechRecognizer?.delegate = self as? SFSpeechRecognizerDelegate  //3

    SFSpeechRecognizer.requestAuthorization { (authStatus) in  //4

        var isButtonEnabled = false

        switch authStatus {  //5
        case .authorized:
            isButtonEnabled = true

        case .denied:
            isButtonEnabled = false
            print("User denied access to speech recognition")

        case .restricted:
            isButtonEnabled = false
            print("Speech recognition restricted on this device")

        case .notDetermined:
            isButtonEnabled = false
            print("Speech recognition not yet authorized")
        }

        OperationQueue.main.addOperation() {
            self.startStopBtn.isEnabled = isButtonEnabled
        }
    }

}


@IBAction func startStopAct(_ sender: Any) {
    if audioEngine.isRunning {
        audioEngine.stop()
        recognitionRequest?.endAudio()
        startStopBtn.isEnabled = false
        startStopBtn.setTitle("Start Recording", for: .normal)
    } else {
        startRecording()
        startStopBtn.setTitle("Stop Recording", for: .normal)
    }

}


func startRecording() {

    if recognitionTask != nil {
        recognitionTask?.cancel()
        recognitionTask = nil
    }

    let audioSession = AVAudioSession.sharedInstance()
    do {
        try audioSession.setCategory(AVAudioSessionCategoryRecord)
        try audioSession.setMode(AVAudioSessionModeMeasurement)
        try audioSession.setActive(true, with: .notifyOthersOnDeactivation)
    } catch {
        print("audioSession properties weren't set because of an error.")
    }

    recognitionRequest = SFSpeechAudioBufferRecognitionRequest()

    let inputNode = audioEngine.inputNode

    guard let recognitionRequest = recognitionRequest else {
        fatalError("Unable to create an SFSpeechAudioBufferRecognitionRequest object")
    }

    recognitionRequest.shouldReportPartialResults = true

    recognitionTask = speechRecognizer?.recognitionTask(with: recognitionRequest, resultHandler: { (result, error) in

        var isFinal = false

        if result != nil {

            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.startStopBtn.isEnabled = true
        }
    })

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

    audioEngine.prepare()

    do {
        try audioEngine.start()
    } catch {
        print("audioEngine couldn't start because of an error.")
    }

    textView.text = "Say something, I'm listening!"

}

func speechRecognizer(_ speechRecognizer: SFSpeechRecognizer, availabilityDidChange available: Bool) {
    if available {
        startStopBtn.isEnabled = true
    } else {
        startStopBtn.isEnabled = false
    }
}

ViewController ScreenShot

谢谢:)

最佳答案

使您的 speechRecognizer 成为 var 而不是 let 属性:

private var speechRecognizer = SFSpeechRecognizer(locale: Locale.init(identifier: "en-US")) 

并在需要时更改它:

speechRecognizer = SFSpeechRecognizer(locale: Locale.init(identifier: "fr-BE"))

关于ios - 我们如何在 swift 4 和 IOS 11 中更改语音识别语言?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52064208/

相关文章:

ios - Swift4 tableview 单元格高度不是动态的并且始终是静态的

ios - 从 AppDelegate 在 WkWebView 中打开 url

web - (连续)网络浏览器中有限单词的语音识别

ios - 加载在线数据很慢很难PUSH

ios - 尽管 UIAlertController 在 View 层次结构中,但呈现一个 ViewController

ios - Autolayout - 在推送新 View Controller 的同时压缩 UINavigationController

ios - UITableViewCell 选中的按钮在滚动 UITableView 时变为未选中状态

swift - NSPredicate:无法解析关系的格式字符串

node.js - 是否可以将 .m4a 文件与 Google Speech to Text API 一起使用?

C# (C++) SAPI - TTS - 如何获取正在阅读的文本的语音计时