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

How can we change speech recognition language in swift 4 and IOS 11?

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

    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
    }
}

}

谢谢:)

使您的语音识别器成为 var 而不是 let 属性:

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

并在需要时更改它:

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