我试图将语音识别代码转换为Swift,ViewController.h中定义的协议为:
@interface ViewController : UIViewController<SpeechRecognitionProtocol>
{
NSMutableString* textOnScreen;
DataRecognitionClient* dataClient;
MicrophoneRecognitionClient* micClient;
SpeechRecognitionMode recoMode;
bool isMicrophoneReco;
bool isIntent;
int waitSeconds;
}
我在ViewController.h的下面转换了函数:
micClient = [SpeechRecognitionServiceFactory createMicrophoneClient:(recoMode)
withLanguage:(language)
withKey:(primaryOrSecondaryKey)
withProtocol:(self)];
此功能在SpeechSDK.framework中定义为:
@interface SpeechRecognitionServiceFactory : NSObject
/*
@param delegate The protocol used to perform the callbacks/events upon during speech recognition.
*/
+(MicrophoneRecognitionClient*)createMicrophoneClient:(SpeechRecognitionMode)speechRecognitionMode
withLanguage:(NSString*)language
withKey:(NSString*)primaryOrSecondaryKey
withProtocol:(id<SpeechRecognitionProtocol>)delegate;
@end
这个协议在我转换的ViewController.Swift中看起来像这样:
import UIKit
protocol SpeechRecognitionProtocol {
func onIntentReceived(result: IntentResult)
func onPartialResponseReceived(response: String)
func onFinalResponseReceived(response: RecognitionResult)
func onError(errorMessage: String, withErrorCode errorCode: Int)
func onMicrophoneStatus(recording: DarwinBoolean)
func initializeRecoClient()
}
class ViewController: UIViewController, SpeechRecognitionProtocol {
var myDelegate: SpeechRecognitionProtocol?
最后我在ViewController.swift中调用了这个函数。在withProtocol之后我收到以下错误:无法转换类型&#39; SpeechRecognitionProtocol.Protocol&#39;预期参数类型&#39; SpeechRecognitionProtocol!&#39; :
func initializeRecoClient() {
let language: String = "en-us"
let path: String = NSBundle.mainBundle().pathForResource("settings", ofType: "plist")!
let settings = NSDictionary(contentsOfFile: path)
let primaryOrSecondaryKey = settings?.objectForKey("primaryKey") as! String
micClient = SpeechRecognitionServiceFactory.createMicrophoneClient(recoMode!,
withLanguage: language,
withKey: primaryOrSecondaryKey,
withProtocol: SpeechRecognitionProtocol)
}
答案 0 :(得分:0)
您不应该自己声明SpeechRecognitionProtocol
(不确定您是仅为了演示目的而添加此内容,还是在代码中实际拥有此内容)。 SpeechRecognitionProtocol
已在SpeechRecognitionService.h
中声明并可供Swift使用 - 这是您需要使用的。
实现该协议的对象是ViewController
。假设您的initializeRecoClient
是该类的方法,则调用需要如下所示:
micClient = SpeechRecognitionServiceFactory
.createMicrophoneClient(recoMode!,
withLanguage: language,
withKey: primaryOrSecondaryKey,
withProtocol: self)
SpeechSDK API没有为该工厂方法选择一个特别好的名称。
withProtocol
参数不接受协议对象本身(顾名思义),而是实现协议的对象(显然)。
P.S。:不确定您使用的SpeechAPI版本,我必须实现这些Swift方法以使ViewController符合SpeechRecognitionProtocol
:
func onPartialResponseReceived(response: String!) {}
func onFinalResponseReceived (response: RecognitionResult) {}
func onError (errorMessage: String!,
withErrorCode errorCode: Int32) {}
func onMicrophoneStatus (recording: Bool) {}
func onIntentReceived (result: IntentResult) {}