LoginSignup
8
6

More than 3 years have passed since last update.

Node.js、Web Speech APIを使って音声認識を出力

Last updated at Posted at 2020-01-23

概要

WebSpeechAPIを使用して聞き取った音声の文字おこしをブラウザ上に表示させます。

作成方法

1.WebSpeechAPIを含むhtmlフォルダの作成

新規フォルダを作成し、その中にindex.htmlを作成。

index.html
<!-- index_voice.html -->

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>音声認識サンプル</title>
</head>
<body>
    <h2>音声認識サンプル</h2>
    <button id="btn">start</button>
    <div id="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を作成し、こちらのコードをコピペします。

var express = require('express');
var app = express();

// public というフォルダに入れられた静的ファイルはそのまま表示
app.use(express.static(__dirname + '/public'));

// bodyParser
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post('/post', function(req, res) {
  for (key in req.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/ でアクセス。
スタートボタンをおして話し、終わりにまたボタンを押すと。
音声認識.PNG

これでひとまず完了です。次に使用してHerokuにデプロイしていきます。(続く)

考察

まずは音声認識APIをつかってアウトプットすることができました。音声の聞き取りの精度もパソコンを目の前にあるような状況、会議とかだったら問題なく拾える制度でした。
次は、Vue.jsでデザインを整えていきます。
また、いまのままではただの文字の羅列になるので、これをどう編集させていくか、プログラムで機能を追加できていければと思います。

8
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
6