Как реализовать Nuance Speechkit при использовании CocoaPods в Swift

Между спецификацией pod и тем, что в данный момент находится на SO, мне было сложно понять, как заставить работать речь в текст, используя SpeechKit + CocoaPod + Swift. Наконец-то все заработало так, что я решил помочь следующей бедной душе, которая ищет помощи!:)

1 ответ

  1. Сначала установите CocoaPod: https://cocoapods.org/pods/SpeechKit
  2. добавлять #import <SpeechKit/SpeechKit.h> к вашему соединительному заголовку
  3. Войдите на портал разработчика Nuance и создайте приложение: https://developer.nuance.com/
  4. Очистите демонстрационный код, чтобы он был более организованным. Я просто хотел, чтобы как можно больше кода было в одном месте, чтобы вы могли видеть полностью работающую реализацию.

Затем создайте UIViewController и добавьте следующий код с правильными учетными данными:

import UIKit
import SpeechKit

class SpeechKitDemo: UIViewController, SKTransactionDelegate {

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


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

//!!link this to a corresponding button on the UIViewController in I.B.
@IBAction func tappedButton(sender: AnyObject) {

    // All fields are required.
    // Your credentials can be found in your Nuance Developers portal, under "Manage My Apps".
    let SKSAppKey = "[Get this from the nuance app info page]";
    let SKSAppId = "[Get this from the nuance app info page]";
    let SKSServerHost = "[Get this from the nuance app info page]";
    let SKSServerPort = "[Get this from the nuance app info page]";

    let SKSLanguage = "eng-USA";

    let SKSServerUrl = "nmsps://\(SKSAppId)@\(SKSServerHost):\(SKSServerPort)"

    let session = SKSession(URL: NSURL(string: SKSServerUrl), appToken: SKSAppKey)


    //this starts a transaction that listens for voice input
    let transaction = session.recognizeWithType(SKTransactionSpeechTypeDictation,
        detection: .Short,
        language: SKSLanguage,
        delegate: self)
    print(transaction)
}

//required delegate methods
func transactionDidBeginRecording(transaction: SKTransaction!) {  }
func transactionDidFinishRecording(transaction: SKTransaction!) {  }
func transaction(transaction: SKTransaction!, didReceiveRecognition recognition: SKRecognition!) {

    //Take the best result
    let topRecognitionText = recognition.text;

    print("Best rec test: \(topRecognitionText)")
    //Or iterate through the NBest list
    let nBest = recognition.details;
    for phrase in (nBest as! [SKRecognizedPhrase]!) {
        let text = phrase.text;
        let confidence = phrase.confidence;
        print("\(confidence): \(text)")
    }



}
func transaction(transaction: SKTransaction!, didReceiveServiceResponse response: [NSObject : AnyObject]!) {  }
func transaction(transaction: SKTransaction!, didFinishWithSuggestion suggestion: String!) {  }
func transaction(transaction: SKTransaction!, didFailWithError error: NSError!, suggestion: String!) {  }



}
Другие вопросы по тегам