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

时间:2018-08-28 18:27:06

标签: 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

谢谢:)

1 个答案:

答案 0 :(得分:4)

为您的SpeechRecognizer设置一个var而不是let属性:

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

并在需要时进行更改:

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