Skip to content

Instantly share code, notes, and snippets.

@arnarthor
Created August 29, 2016 13:10
Show Gist options
  • Save arnarthor/ef6672f5f7c8c777c10e04c471255883 to your computer and use it in GitHub Desktop.
Save arnarthor/ef6672f5f7c8c777c10e04c471255883 to your computer and use it in GitHub Desktop.
/* @flow */
import _ from 'lodash';
import React, {Component} from 'react';
import makeDebug from 'debug';
import styles from './index.css';
const debug = makeDebug('component:SpeechRecognition');
type Props = {
onChange: Function,
onEnd: Function,
}
type SpeechRecognitionResult = {
isFinal: boolean,
'0': {
confidence: number,
transcript: string,
},
}
type SpeechRecognitionResults = {
results: Array<SpeechRecognitionResult>,
}
export default class EditableTitle extends Component {
props: Props
recognizer: null
componentDidMount() {
// $FlowSuppressError
const SpeechRecognition = SpeechRecognition || webkitSpeechRecognition; // eslint-disable-line
if (!SpeechRecognition) {
alert('This is an unsupported feature in your browser');
} else {
this.recognizer = new SpeechRecognition();
this.recognizer.lang = 'en-US';
this.recognizer.interimResults = 'en-US';
this.recognizer.continuous = true;
this.recognizer.onresult = (data) => this.readVoice(data);
}
}
render() {
return (
<div
className={styles.container}
onClick={() => this.record()}
>
Record
</div>
);
}
record() {
this.recognizer && this.recognizer.start();
}
findFinal(data: SpeechRecognitionResults) {
// $FlowSuppressError
return _.filter(data.results, (result: SpeechRecognitionResult) => {
return result.isFinal;
});
}
readVoice(data: SpeechRecognitionResults) {
const finals = this.findFinal(data);
if (finals.length > 0) {
this.recognizer && this.recognizer.stop();
const sentence = _.map(finals, (part) => {
return part[0].transcript;
}).join('');
this.props.onEnd(sentence);
} else {
const sentence = _.map(data.results, (part) => {
return part[0].transcript;
}).join('');
this.props.onChange(sentence);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment