gogo2/agent-mobile/artimobile/VoiceHandler.js

73 lines
1.5 KiB
JavaScript

// VoiceHandler.js
import React, { Component } from 'react';
import { View, Text, Button } from 'react-native';
import Voice from '@react-native-voice/voice';
class VoiceHandler extends Component {
constructor(props) {
super(props);
this.state = {
recognized: '',
started: '',
results: [],
};
Voice.onSpeechStart = this.onSpeechStart.bind(this);
Voice.onSpeechRecognized = this.onSpeechRecognized.bind(this);
Voice.onSpeechResults = this.onSpeechResults.bind(this);
}
componentWillUnmount() {
Voice.destroy().then(Voice.removeAllListeners);
}
onSpeechStart(e) {
this.setState({
started: '√',
});
}
onSpeechRecognized(e) {
this.setState({
recognized: '√',
});
}
onSpeechResults(e) {
this.setState({
results: e.value,
});
}
async _startRecognizing(e) {
this.setState({
recognized: '',
started: '',
results: [],
});
try {
await Voice.start('en-US');
} catch (e) {
console.error(e);
}
}
render() {
return (
<View>
<Text>Press the button and start speaking.</Text>
<Button
onPress={this._startRecognizing.bind(this)}
title="Start Recognizing"
/>
<Text>Recognized: {this.state.recognized}</Text>
<Text>Started: {this.state.started}</Text>
<Text>Results: {this.state.results.join(' ')}</Text>
</View>
);
}
}
export default VoiceHandler;