free pascal:fpwebview 组件通过 JSBridge 调用本机TTS

2024-02-16 11:52

本文主要是介绍free pascal:fpwebview 组件通过 JSBridge 调用本机TTS,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

从 https://github.com/PierceNg/fpwebview 下载 fpwebview-master.zip 简单易用。

先请看 \fpwebview-master\README.md

cd \lazarus\projects\fpwebview-master\demo\js_bidir

学习 js_bidir.lpr ,编写 js_bind_speak.lpr 如下,通过 JSBridge 调用本机TTS。

program js_bind_speak;{$linklib libwebview}
{$mode objfpc}{$H+}uses{$ifdef unix}cthreads,{$endif}Classes,Process,SysUtils,StrUtils,Variants,ComObj, math,webview;varw: PWebView;sapi: Variant;url: String;txt: String;// seq:sequence; req:request; arg:argument
procedure speak(const seq: PAnsiChar; const req: PAnsiChar; arg: Pointer); cdecl;
vars: String;
beginif req <> nil thenbegins := strPas(req);writeln('speak:'+s);trysapi.Speak(s);Sleep(1000)exceptwriteln(' OLE Error ')  end;endelsewriteln(' req is nil');//webview_return(w, seq, WebView_Return_Ok, '{result: "?"}');
end;beginif Assigned(InitProc) thenTProcedure(InitProc);{ Set math masks. libwebview throws at least one of these from somewhere deep inside. }SetExceptionMask([exInvalidOp, exDenormalized, exZeroDivide, exOverflow, exUnderflow, exPrecision]);trysapi := CreateOleObject('SAPI.SpVoice')exceptwriteln(' OLE Error ')end;url := 'http://localhost/';if ParamCount =1 thenbeginif Length(ParamStr(1))<6 thenurl := 'http://localhost:' + ParamStr(1)elsebeginif AnsiStartsStr('http', ParamStr(1)) then url := ParamStr(1)else if AnsiStartsStr('192.', ParamStr(1)) then url := 'http://' + ParamStr(1)else url := 'https://' + ParamStr(1);end;endelseurl := ParamStr(1);writeln(url);w := webview_create(WebView_DevTools, nil);webview_set_size(w, 1024, 768, WebView_Hint_None);webview_set_title(w, PAnsiChar('WebView - Pascal Javascript Bridge'));
//webview_bind(w: PWebView; const name: PAnsiChar; fn: TWebViewBindProc; arg: Pointer);webview_bind(w, PAnsiChar('sapi_speak'), @speak, PAnsiChar(txt));webview_navigate(w, PAnsiChar(url));webview_run(w);webview_destroy(w);
end.

注意这一句:webview_bind(w, PAnsiChar('sapi_speak'), @speak, PAnsiChar(txt));

编写 编译批命令:winbuild.bat  如下

@echo offecho Set up FPC executable path.
set fpcexe=D:\lazarus\fpc\3.2.2\bin\x86_64-win64\fpc.exe
if not exist "%fpcexe%" (echo ERROR: Edit this batch file to set up location of fpc.exeexit /b 1
)
echo "%fpcexe%"echo Building...
copy "..\..\dll\x86_64\libwebview.a" .
copy "..\..\dll\x86_64\webview.dll" .
copy "..\..\dll\x86_64\WebView2Loader.dll" .
"%fpcexe%" -Fu..\..\src -Fl. js_bind_speak.lpr

编写 运行批命令:winrun.bat  如下

@echo off
@echo js_bind_speak.exe 
js_bind_speak.exe  %1

前端 js 代码:index6.html  如下

<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0">   <title>查询英汉词典</title> <script src="jquery-3.2.1.min.js"></script>
<style>
/* portrait 判断为竖屏 */
@media only screen and (orientation: portrait){#lab1 {display:none;}
} 
/* landscape 判断为横屏 */ 
@media only screen and (orientation: landscape){#lab1 {display: ;} 
}    
</style>
</head>
<body><form name="form" id="form" action="trans" method="POST" target="iframe"><label id="lab1">请输入:</label><input type="text" name="txt" id='txt' size="30" placeholder="请输入 a word"><input type="submit" name="eng_han" value="英译汉"><input type="button" name="btn1" id="btn1" value="前缀查询"><input type="button" name="btn2" id="btn2" value="TTS读音" onclick="tts2()"></form><p></p>
<div style="float:left; width:100%;"><div id="result" style="float:left; width:80%; height:400; border:2px;"><iframe name="iframe" id="iframe" width="100%" height="400"> </iframe></div><div id="alist" style="float:right; width:20%; height:400; border:2px;"></div>
</div><script type="text/javascript">$(function(){$("#btn1").click(function(){$.getJSON("/prefix?txt="+$("#txt").val(), function(data){$('#alist').empty();var items = [];$.each(data, function(i, item){if (i<=20){items[i] = '<a href="/trans?txt=' +item+ '" target="iframe">' +item+ "</a><br>";}});var a = items.join('\n');if (a) $('#alist').html(a);})})});//定义对象 customHost,方便js函数调用//var hostObj = window.chrome.webview.hostObjects.customHost;// pascal TTSfunction tts() {var txt = document.getElementById('txt').value;if (txt.length >1) {(async ()=>{await sapi_speak(txt);})();}}// 屏幕双击取词, pascal TTSfunction tts2() {// 获取iframe里的选择内容var select = window.frames['iframe'].getSelection();var txt = select.toString();txt = txt.trim();if (txt.length >1) { // alert(txt);(async ()=>{await sapi_speak(txt);})();} else {tts();}}// 页面加载添加:监听iframe网页点击事件$(document).ready(function(){var listener = window.addEventListener('blur', function(){if (document.activeElement === document.getElementById('iframe')){$('iframe').contents().find('a.fayin').click(function(event){event.preventDefault();var a = $(this);if (a){var addr = a.attr('href');if (addr.indexOf('sound://')==0){var url = "/data" + addr.substring(7);var mp3 = new Audio(url);mp3.addEventListener("canplaythrough", (event)=> {mp3.play();});} else {alert('href='+addr);}}})}        });});
</script> 
</body>
</html>

web 服务程序请参考:python:mdict + bottle = web 查询英汉词典

记得修改一句:def server_static(filepath="index6.html"):

先运行 web 服务程序:python mdict_bottle.py

再执行编译:winbuild.bat

最后运行:winrun.bat 8086

访问  http://localhost:8086/

这篇关于free pascal:fpwebview 组件通过 JSBridge 调用本机TTS的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/714450

相关文章

Java中调用数据库存储过程的示例代码

《Java中调用数据库存储过程的示例代码》本文介绍Java通过JDBC调用数据库存储过程的方法,涵盖参数类型、执行步骤及数据库差异,需注意异常处理与资源管理,以优化性能并实现复杂业务逻辑,感兴趣的朋友... 目录一、存储过程概述二、Java调用存储过程的基本javascript步骤三、Java调用存储过程示

Python中Tensorflow无法调用GPU问题的解决方法

《Python中Tensorflow无法调用GPU问题的解决方法》文章详解如何解决TensorFlow在Windows无法识别GPU的问题,需降级至2.10版本,安装匹配CUDA11.2和cuDNN... 当用以下代码查看GPU数量时,gpuspython返回的是一个空列表,说明tensorflow没有找到

python如何调用java的jar包

《python如何调用java的jar包》这篇文章主要为大家详细介绍了python如何调用java的jar包,文中的示例代码简洁易懂,具有一定的借鉴价值,有需要的小伙伴可以参考一下... 目录一、安装包二、使用步骤三、代码演示四、自己写一个jar包五、打包步骤六、方法补充一、安装包pip3 install

Java调用C#动态库的三种方法详解

《Java调用C#动态库的三种方法详解》在这个多语言编程的时代,Java和C#就像两位才华横溢的舞者,各自在不同的舞台上展现着独特的魅力,然而,当它们携手合作时,又会碰撞出怎样绚丽的火花呢?今天,我们... 目录方法1:C++/CLI搭建桥梁——Java ↔ C# 的“翻译官”步骤1:创建C#类库(.NET

Spring组件实例化扩展点之InstantiationAwareBeanPostProcessor使用场景解析

《Spring组件实例化扩展点之InstantiationAwareBeanPostProcessor使用场景解析》InstantiationAwareBeanPostProcessor是Spring... 目录一、什么是InstantiationAwareBeanPostProcessor?二、核心方法解

C/C++和OpenCV实现调用摄像头

《C/C++和OpenCV实现调用摄像头》本文主要介绍了C/C++和OpenCV实现调用摄像头,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录准备工作1. 打开摄像头2. 读取视频帧3. 显示视频帧4. 释放资源5. 获取和设置摄像头属性

C++ RabbitMq消息队列组件详解

《C++RabbitMq消息队列组件详解》:本文主要介绍C++RabbitMq消息队列组件的相关知识,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. RabbitMq介绍2. 安装RabbitMQ3. 安装 RabbitMQ 的 C++客户端库4. A

使用Python实现调用API获取图片存储到本地的方法

《使用Python实现调用API获取图片存储到本地的方法》开发一个自动化工具,用于从JSON数据源中提取图像ID,通过调用指定API获取未经压缩的原始图像文件,并确保下载结果与Postman等工具直接... 目录使用python实现调用API获取图片存储到本地1、项目概述2、核心功能3、环境准备4、代码实现

使用@Cacheable注解Redis时Redis宕机或其他原因连不上继续调用原方法的解决方案

《使用@Cacheable注解Redis时Redis宕机或其他原因连不上继续调用原方法的解决方案》在SpringBoot应用中,我们经常使用​​@Cacheable​​注解来缓存数据,以提高应用的性能... 目录@Cacheable注解Redis时,Redis宕机或其他原因连不上,继续调用原方法的解决方案1

C#通过进程调用外部应用的实现示例

《C#通过进程调用外部应用的实现示例》本文主要介绍了C#通过进程调用外部应用的实现示例,以WINFORM应用程序为例,在C#应用程序中调用PYTHON程序,具有一定的参考价值,感兴趣的可以了解一下... 目录窗口程序类进程信息类 系统设置类 以WINFORM应用程序为例,在C#应用程序中调用python程序