我想知道responsivevoice (JS) 何时结束讲话。在文档中here ,它表明我可以传递像 onstart/onend 这样的回调。因此,我制作了一个 JSInterface 并将其附加到调用我的 JS 函数的 WebView。但是,我一定没有正确执行此操作,因为我的回调从未被输入。
这是我的 JSInterface:
private class JSInterface{
@JavascriptInterface
public void alertStart(){
Log.i(TAG, "Speech started");
}
@JavascriptInterface
public void stopService(){
stopSelf(); //The whole point of this is to stop my Service.
}
}
这里我将界面附加到webview:
final WebView webView = new WebView(context);
webView.setSoundEffectsEnabled(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new JSInterface(), "SpeechService");
这是我的 JS 函数:
function speak(text,voice,pitch,rate) {
responsiveVoice.speak(text, voice,
{
onstart: alertStart,
onend: stopService
}
);
}
function alertStart(){
SpeechService.alertStart();
}
function stopService(){
SpeechService.stopService();
}
我从这里的服务中使用我的 webView 调用该函数:
webView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
if (sp.contains("voiceSettings")) {
String voiceSettings = sp.getString("voiceSettings", "Voice settings not available");
final String splitSettings[] = voiceSettings.split(":");
Log.i("settings", Arrays.toString(splitSettings));
webView.loadUrl("javascript:speak('" + text + "','" + splitSettings[0] + "','" + Double.parseDouble(splitSettings[1]) + "','" + Double.parseDouble(splitSettings[2]) + "')");
}
else{
webView.loadUrl("javascript:speak('" + text + "','" + "UK English Male" + "','" + 1 + "','" + 1 + "')");
}
}
});
webView.loadUrl("file:///android_asset/tts.html");
}
提前致谢
最佳答案
结果是,发送给 JS 函数的字符串中有一个撇号,这导致语法不正确。所以该函数从未被调用。必须将输入用双引号括起来,以便将所有撇号括起来。
关于android JSInterface 无法到达 JavaScript 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38289738/