【发布时间】:2019-07-04 16:26:40
【问题描述】:
在您阅读本文之前,它可能与 How can a Chrome extension get a user's permission to use user's computer's microphone? 如果有帮助,我在下面添加了一个答案,包括代码和我的清单。
我正在编写一个最小的 Chrome 扩展程序(在 MacOS 10.14.5 上使用 Chrome 75.0.3770.90)来为我的辅助功能项目实现一个“收听”按钮。我用适用于麦克风的 JavaScript 编写了一个 HTML 版本。
但是,当我将该代码提升到 Extension background.js 文件中时,文本转语音可以正常工作,但语音转文本无效。代码运行,但闪烁的麦克风从未出现在选项卡中。
有效的代码是:
<!DOCTYPE html>
<html>
<body>
<h2>All-in-one JavaScript Example</h2>
<button onclick="myCode();">Listen</button>
<script>
window.SpeechRecognition = window.webkitSpeechRecognition
|| window.SpeechRecognition;
function myCode() {
recognition = new SpeechRecognition();
recognition.start();
recognition.onresult = function(event) {
if (event.results[0].isFinal) {
response = event.results[0][0].transcript;
synth = window.speechSynthesis;
synth.speak( new SpeechSynthesisUtterance(
"i don't understand, "+response
));
} }
alert( "all-in-one: we're done!" );
}
</script>
</body>
</html>
最小的可重现示例:
{
"name": "myName",
"description": "Press to talk",
"version": "0.97",
"manifest_version": 2,
"background": {
"scripts": ["background.js"],
"persistent": false
},
"permissions": ["contentSettings","desktopCapture","*://*/*","tabCapture","tabs","tts","ttsEngine"],
"browser_action": {
"default_icon": "images/myIcon512.png",
"default_title": "Press Ctrl(Win)/Command(Mac)+Shift+ Down to speak"
},
"commands": {
"myCommand": {
"suggested_key": {
"default": "Ctrl+Shift+Down",
"mac": "Command+Shift+Down"
},
"description": "Start speaking"
}
},
"icons": {
"512": "images/myIcon512.png"
}
}
我的后台 JavaScript 是:
window.SpeechRecognition = window.webkitSpeechRecognition || window.SpeechRecognition;
function myCode() {
var recognition = new SpeechRecognition();
recognition.onresult = function(event) {
if (event.results[0].isFinal) {
var synth = window.speechSynthesis;
synth.speak( new SpeechSynthesisUtterance(
"sorry, I don't understand."
)
);
}
}
recognition.start();
alert( "extension: we're done!" );
}
chrome.commands.onCommand.addListener(function(command) {
if (command === 'myCommand')
myCode();
});
我还注意到代码只运行一次 - 我可以继续单击监听按钮,但扩展命令只运行一次(在函数开头添加警报只会在第一次显示)
我的浏览器的默认设置是它应该(一次)询问它在 HTML 版本上做了什么。
感谢您阅读到这里!我已经用代码在下面给出了答案。
【问题讨论】:
标签: javascript google-chrome-extension speech-recognition