概要
WebSpeechAPIを使用して聞き取った音声の文字おこしをブラウザ上に表示させます。
作成方法
1.WebSpeechAPIを含むhtmlフォルダの作成
新規フォルダを作成し、その中にindex.htmlを作成。
index.html
<!-- index_voice.html --><!DOCTYPE html><htmllang="ja"><head><metacharset="UTF-8"><title>音声認識サンプル</title></head><body><h2>音声認識サンプル</h2><buttonid="btn">start</button><divid="content"></div><script>//ここに音声認識の処理を書いていく</script><body><html>音声認識をするための処理をscriptタグ内に書いていきます。
index.html
//ここに音声認識の処理を書いていく
const speech = new webkitSpeechRecognition();
speech.lang = 'ja-JP';
</script>音声認識を実行する準備はこの2行で完了です。
webkitSpeechRecognition()を定義し、langをja-JPにすることで日本語に対応したWeb Speech APIが使えるようになります。
そしてこれをイベントで実行出来るようにしていきます。
index.html
//ここに音声認識の処理を書いていく
const speech = new webkitSpeechRecognition();
speech.lang = 'ja-JP';
//---------------追記---------------//
const btn = document.getElementById('btn');
const content = document.getElementById('content');
btn.addEventListener('click' , function() {
// 音声認識をスタート
speech.start();
});
speech.addEventListener('result' , function(e) {
// 音声認識で取得した情報を、コンソール画面に表示
console.log(e);
//---------------追記---------------//
// 音声認識で取得した情報を、HTMLに表示
const text = e.results[0][0].transcript;
content.innerText = text;
//--------------------------------//
});
//--------------------------------//
</script>2.サーバー立ち上げ
node.js Expressを使ってローカルサーバーの立ち上げを行います。
Web speech Api-sampleというフォルダー作成します。
初期設定します。
npm init -y
必要なライブラリをインストールします。
npm i body-parser express
index.jsを作成し、こちらのコードをコピペします。
varexpress=require('express');varapp=express();// public というフォルダに入れられた静的ファイルはそのまま表示app.use(express.static(__dirname+'/public'));// bodyParservarbodyParser=require('body-parser');app.use(bodyParser.json());app.post('/post',function(req,res){for(keyinreq.body){console.log(key,'=',req.body[key]);}res.end();});app.listen(process.env.PORT||8080);console.log("server start! (heroku)");こちらをindex.jsで保存します。
index.js と同じ階層に public フォルダを作りその中に 先ほど作成したindex.html を格納します。
node index.js
実行します。
http://localhost:8080/でアクセス。
スタートボタンをおして話し、終わりにまたボタンを押すと。
これでひとまず完了です。次に使用してHerokuにデプロイしていきます。(続く)
考察
まずは音声認識APIをつかってアウトプットすることができました。音声の聞き取りの精度もパソコンを目の前にあるような状況、会議とかだったら問題なく拾える制度でした。
次は、Vue.jsでデザインを整えていきます。
また、いまのままではただの文字の羅列になるので、これをどう編集させていくか、プログラムで機能を追加できていければと思います。