LoginSignup
2
3

More than 3 years have passed since last update.

Yandex Translation API を使って翻訳機能を試す

Last updated at Posted at 2020-04-17

はじめに

音声認識を試してみたら、翻訳できたら便利だなと思ったので、簡単に使えそうなAPIを探してみた
前回:Speech Recognition API でブラウザ音声認識を試す

YandexTranslation

概要

  • Yandexがロシア版Googleみたいなもので、そのYandexが出してる翻訳API
  • APIの使用には無料登録が必要
  • 使い方が簡単そうだったの試しに使ってみた

準備

Yandexに登録

登録画面
1.PNG

YandexAPIを発行

サインインしてAPI一覧ページに飛んだら
+ Create a new key からAPIキーを発行
2.PNG

使用方法

公式ページドキュメントによると

https://translate.yandex.net/api/v1.5/tr.json/translate
 ? key=<API key>
 & text=<text to translate>
 & lang=<translation direction>
 & [format=<text format>]
 & [options=<translation options>]
 & [callback=<name of the callback function>]

ということなので、URLに当てはめてHTTPのGETリクエストを投げることにした。

テキスト翻訳してみる

仕様

  1. inputに単語を入力
  2. translateボタン押下 → 翻訳開始
  3. ログに翻訳結果が出る
translationTest.html
<!DOCTYPE html>
<html>

<head lang="ja-JP">
    <meta charset="utf-8">
    <title>Translation Test</title>
</head>

<body>

    <input id="input_text" placeholder="input a word here">
    <button onclick="translatebutton()">translate</button>

    <script>
        const base_url = "https://translate.yandex.net/api/v1.5/tr.json/translate"
        const api_key = "XXXXXXXXXXXXXXXXXXXXX" // 発行したAPIKeyを入力
        const format = "html"

        function translatebutton() {
            console.log("translate")

            const text = document.getElementById("input_text").value
            const lang = "en" // 英語に翻訳する。"ja"にすれば日本語に翻訳する
            const url = base_url + '?key=' + api_key + "&text=" + text + "&lang=" + lang + "&format=" + format

            const request = new XMLHttpRequest();
            request.open('GET', url);
            request.onreadystatechange = function () {
                if (request.readyState != 4) {
                } else if (request.status != 200) {
                    console.log("http request failed.")
                } else {
                    console.log("success", request.responseText);
                }
            };
            request.send(null);
        }

    </script>
</body>

</html>

結果

うまくいきました
4.PNG

2
3
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
2
3