Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to change language in UI with UISegmentedControl, I thought to make different instance as attribute for ViewControler class like

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

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

It is a way but for sure no the best way I am wondering Could you folks give me better idea How can I do ?

Here is app source code that we type what ever user say in english but we want to give option to user to change language :

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

Thanks :)

like image 562
AMH Avatar asked Jan 01 '23 22:01

AMH


1 Answers

Make your speechRecognizer a var instead of a let property:

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

And change it whenever you need to:

speechRecognizer = SFSpeechRecognizer(locale: Locale.init(identifier: "fr-BE"))
like image 124
ielyamani Avatar answered Jan 05 '23 04:01

ielyamani