Watson STT(Speech to Text)を React で実装する方法についてです。
最初は Cordova のプラグインで探していたのですが、認証がユーザ名とパスワードを使用する、少し古いタイプだったので、使用を断念…。
代わりに、下記の記事を参考に、React で実装しました。
Watsonで入門するリアルタイム音声認識 – Qiita
https://qiita.com/ovrmrw/items/a0b29d6959333c5a746c
全コードが載っているので、ほぼコピー&ペーストで実装しました。
ただ、getTokenAsync() でトークンを取得しているのですが、こちらは別途、API を開発する必要があります。
コードはこちら。
import React, { Component } from 'react';
import recognizeMic from 'watson-speech/speech-to-text/recognize-microphone';
class WatsonSTTPage extends Component {
constructor(props) {
super(props);
this.state = {
token: null,
isRecording: false,
recognizeStream: null,
transcripts: [],
};
this.toggleMicrophoneState = this.toggleMicrophoneState.bind(this);
this.startRecognizeStream = this.startRecognizeStream.bind(this);
this.stopRecognizeStream = this.stopRecognizeStream.bind(this);
this.getTokenAsync = this.getTokenAsync.bind(this);
}
getTokenAsync() {
// 要変更
return fetch('[URL]')
.then(res => res.json())
.then(data => data.token);
}
toggleMicrophoneState() {
if (this.state.recognizeStream) {
this.stopRecognizeStream();
} else if (!this.state.isRecording) {
this.setState({ isRecording: true });
this.getTokenAsync()
.then(token => {
this.setState({ transcripts: [] });
this.startRecognizeStream(token);
});
}
}
startRecognizeStream(token) {
const stream = recognizeMic({
token,
model: 'ja-JP_BroadbandModel',
objectMode: true,
extractResults: true,
});
stream.on('data', data => {
if (data.final) {
const transcript = data.alternatives[0].transcript;
this.setState({ transcripts: [...this.state.transcripts, transcript] });
}
});
this.setState({ recognizeStream: stream });
}
stopRecognizeStream() {
if (this.state.recognizeStream) {
this.state.recognizeStream.stop();
this.state.recognizeStream.removeAllListeners();
}
this.setState({ isRecording: false,
recognizeStream: null });
}
render() {
return (
<div>
<textarea>{this.state.transcripts.join(', ')}</textarea>
<button onClick={this.toggleMicrophoneState}>{!this.state.isRecording ? 'Watson STT 起動' : 'Watson STT 終了'}</button>
</div>
);
}
}
export default WatsonSTTPage;
必要最低限なので、必要に応じて修正してください。
以上、React で Watson Speech to Text を実装する方法でした。
まだ完成ではありませんが、残るは API でトークンを取得するだけなので、ほぼほぼOKかなと思います。
是非、参考にしていただければ幸いです。