https://developer.yahoo.co.jp/webapi/jlp/furigana/v2/furigana.html

https://developer.yahoo.co.jp/webapi/jlp/sample/sample10.html

 

yahoo さんの API で 漢字にルビを振ってくれるAPIがありこれを使ってみます。

Andorid Text to Speech が日本語だとかなりへんてこりんな読み方をするので、漢字にルビを振って利用します。

import 'dart:convert';
import 'package:http/http.dart' as http;

Future<List<String>> getFurigana(String text, String appId) async {
  final apiUrl = Uri.parse('https://jlp.yahooapis.jp/FuriganaService/V2/furigana');

  final requestBody = jsonEncode({
    'id': '1',
    'jsonrpc': '2.0',
    'method': 'jlp.furiganaservice.furigana',
    'params': {
      'q': text,
      'grade' : 1
    },
  });

  final response = await http.post(apiUrl, headers: {'Content-Type': 'application/json', 'User-Agent': 'Yahoo AppID: $appId'},body: requestBody);
  // print(response.body);
  final jsonData = jsonDecode(response.body);
  final wordList = jsonData['result']['word'] as List<dynamic>;
  // print(wordList);

  List<String> textList = [];
  String _text = '';
  for (var word in wordList) {
    var singleWord = word.containsKey('furigana') ? word['furigana'] : word['surface'];
    _text +=  singleWord;
    print (_text);
    // 改行文字を比較
    if (singleWord == '\n') {
      textList.add(_text);
      _text = '';
    }
  }
  return textList;
}

void main() async {
  const appId = ''; // 自分のアプリケーションIDに置き換えてください
  const text = '''
私はケンです。
私は学生です。
私は旅行者です。
''';

  final furiganaText = await getFurigana(text, appId);
  print(furiganaText);
}
// 結果
[わたしはケンです。
, わたしはがくせいです。
, わたしはりょこうしゃです。
]

response の json がいまいち直感的でない感じでした。

ChatGPT さんに相談しながら作りました。

Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)

© 2024 Falco Tech Blog Suffusion theme by Sayontan Sinha