LoginSignup
1
3

More than 5 years have passed since last update.

ExpoのSpeechを使って文字列を読み上げる方法

Last updated at Posted at 2019-02-25

Speech.speak()を使って再生

読み上げたい文字列をExpoが用意してくれているSpeech.speak()に引数として渡してあげるだけで
文字列を読み上げてくれる。
以下のコードはボタンを押すと「おはようございます。今日もいい天気ですね。」と読み上げ音声が流れるだけの簡単なサンプル。

App.js
import React from 'React';
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';
import { Speech } from 'expo';

export default Class App extends React.Component {
  startSpeech = () => {
    const text = 'おはようございます。今日もいい天気ですね。'
    Speech.speak(text, {language: 'ja', rate: 1.0, pitch: 1.0})
  }
  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity style={styles.button} onPress={() => this.startSpeech()}>
          <Text style={styles.buttonItem}>Start Speech</Text>
        </TouchableOpacity>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  //styleは省略
})

ポイント

  • expoからSpeechをインポート → これでSpeechが使えるようになる。
  • Speech.speak()に渡す引数は2つで、1つはtext、もう1つはoptions。

textはただの文字列。読み上げさせたい文字列を渡そう。

optionsには読み上げる際の言語や読み上げ速度(rate)、ピッチ(pitch)そして他にもコールバック関数(onStartなど)をオブジェクトの形で入れる。不要な場合は省略可。

読み上げる際の言語指定は言語コードを参照。(日本語なら'jp'、英語なら'en'、スペイン語なら'es'など…)

ちょっとハマった注意点

日本語で読み上げる時に少し困った点。

iOSで動かす場合はSiriさんの声で読み上げてくれるため日本語でも問題なかったが、Android端末の場合は日本語に対応していない場合があるみたい。

英語は読み上げてくれたのに日本語にしたらウンともスンとも言わんやんけ!と思ったらOSの方の問題かも。

他のメソッド

他にも読み上げを一時停止するSpeech.pause()や再開するSpeech.resume()などもあるけどここでは割愛。

詳しくは公式ドキュメントを読むのがいい。このメソッドに関して言えば特に難しいことはない。

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