我已经复制了一个使用javascript编写的带有画布的开源网络游戏,并且我想实现“反应语音识别” API(https://www.npmjs.com/package/react-speech-recognition)
要使用此API,我需要创建一个可呈现HTML的react应用。是否有可能创建一个带有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);
如何使用该示例代码并使用简单的方法创建一个可调用它们的类?
谢谢。
答案 0 :(得分:1)
在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是一个很好的资源。