我复制了一个用 javascript 编写的带有 Canvas 的开源网页游戏,我想实现“react-speech-recognition”API( https://www.npmjs.com/package/react-speech-recognition )
要使用此 API,我需要创建一个呈现 HTML 的 React 应用程序。是否可以创建一个简单的类,我可以在我的 javascript 代码中导入和使用它?
这是 react 中的代码:
import React, { Component } from "react";
import PropTypes from "prop-types";
import SpeechRecognition from "react-speech-recognition";
const propTypes = {
// Props injected by SpeechRecognition
transcript: PropTypes.string,
resetTranscript: PropTypes.func,
browserSupportsSpeechRecognition: PropTypes.bool
};
const Dictaphone = ({
transcript,
resetTranscript,
browserSupportsSpeechRecognition
}) => {
if (!browserSupportsSpeechRecognition) {
return null;
}
return (
<div>
<button onClick={resetTranscript}>Reset</button>
<span>{transcript}</span>
</div>
);
};
Dictaphone.propTypes = propTypes;
export default SpeechRecognition(Dictaphone);
我如何使用该示例代码并创建一个具有简单方法的类来调用它们?
谢谢。
最佳答案
react-speech-recognition
描述中的链接是对 SpeechRecognition API 的引用其中包括一些示例。从那里复制:
var grammar = '#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;'
var recognition = new SpeechRecognition();
var speechRecognitionList = new SpeechGrammarList();
speechRecognitionList.addFromString(grammar, 1);
recognition.grammars = speechRecognitionList;
//recognition.continuous = false;
recognition.lang = 'en-US';
recognition.interimResults = false;
recognition.maxAlternatives = 1;
var diagnostic = document.querySelector('.output');
var bg = document.querySelector('html');
document.body.onclick = function() {
recognition.start();
console.log('Ready to receive a color command.');
}
recognition.onresult = function(event) {
var color = event.results[0][0].transcript;
diagnostic.textContent = 'Result received: ' + color;
bg.style.backgroundColor = color;
}
一个好的做法是检查哪些浏览器将支持您的代码 - caniuse.com是一个很好的资源。
关于javascript - 是否可以在不使用 React 应用程序的情况下使用 React-Speech-Recognition?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57672761/