LoginSignup
8
6

More than 5 years have passed since last update.

Web Speech APIをAngularJSで試す

Last updated at Posted at 2014-12-10

AngularJS Advent Calendar 2014 11日目

概要

音声スピーチ機能に興味があったのでWeb Speech APIを使ったディレクティブを作ってみました。これであなたのサイトのアクセシビリティは激アップ!!(爆)

Chrome、Safariで動きます(2014/12/10現在) ⇒ Can I Use

実装

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>Web Speech API</title>
</head>
<body ng-app="app">
    <div>
        <div speech>テスト</div>
        <div speech>そこにしびれるあこがれるぅぅぅ!!</div>
        <div speech lang="en-US">Hi I'm speeker</div>
        <input type="text" ng-model="inputText" placeholder="入力してね">
        <div speech ng-bind="inputText" ></div>
    </div>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.6/angular.min.js"></script>
    <script type="text/javascript" src="app.js"></script>
    <script type="text/javascript" src="speech.js"></script>
</body>
</html>
app.js
angular.module("app", ["speech"]);
speech.js
var app = angular.module("speech", []);

// Speech service
app.service("speech", function() {
    this.speak = function(text, options) {
        options = angular.extend({
            "volume": 1,
            "rate"  : 1,
            "pitch" : 2,
            "lang"  : "ja-JP"
        }, options);
        var msg = new SpeechSynthesisUtterance();
        msg.volume = options["volume"];
        msg.rate = options["rate"];
        msg.pitch = options["pitch"];
        msg.lang = options["lang"];
        msg.text = text;
        speechSynthesis.speak(msg);
    }; 
});

// Speech directive
app.directive("speech", ["speech", function(speech) {
    return {
        restrict: "A",
        link: function(scope, element, attrs) {
            var lang = attrs.lang || "";

            element.bind("click", function() {
                var text = angular.element(element).text();
                var options = {};
                if (lang) {
                    options["lang"] = lang;
                }
                speech.speak(text, options);
            });
        }
    };
}]);

サンプル

テキストをクリックすると、しゃべります

まとめ

  • 想像以上に手軽で、ほとんどコードを書く必要がなかった・・・。
  • Web Speech APIには音声入力の機能も含まれてるため、input要素と組み合わせも可能

※当初はVoiceText Web APIなるWeb上の音声合成APIと組み合わせる予定だったが、中継サーバーが必要なためこれを使うのは別の機会に

参考

[HTML5] Web Speech APIに入門
http://www.yoheim.net/blog.php?q=20140701

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