1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【React Native(Expo)】expo-speechを使ってのテキスト音声読み上げ

Posted at

本記事を作成したきっかけ

現在、G'sACADEMYという学校で、
日々プログラミングの勉強に励んでおり、
卒業制作でReact Native(Expo)を使って
モバイルアプリの開発を行っております。
(未完成機能はありますが、3月末に提出済)

プロダクト自体はまだまだですが、
制作期間でのやったことを振り返って
OUTPUTしたい気持ちが芽生え、記事作成という方法で
OUTPUTしようと思った次第です。

expo-speechとは

Expoを利用したReact Nativeのアプリで、
テキストを音声読み上げするためのライブラリです。

実行環境

Expo:52.0.36
react-native:0.76.7
expo-speech:13.0.1

実装例

speechSample.ts
import { router } from "expo-router"
import { useState } from "react"
import { Appbar, Text } from "react-native-paper"
import { SafeAreaView } from "react-native-safe-area-context"

// 本記事対象のライブラリです。
import * as ExpoSpeech from "expo-speech"

// 改行付きでテキスト作成
const text: string = "こんにちは!\nお元気ですか?\n私は元気です。"
export default function Speech() {

    const [isSpeaking, setIsSpeaking] = useState<boolean>(false)

    /**
     * テキストを音声合成する関数
     * isSpeaking状態がtrueの場合は音声合成を停止する
     * isSpeaking状態がfalseの場合は音声合成を開始する
     * 
     * @remarks
     * ExpoSpeech.speak()で音声合成を実行し、完了した場合はisSpeakingをfalseに戻す
     * エラーが発生した場合はisSpeakingをfalseに戻す
     */
    const handleSpeech = () => {
        // 再生中の場合は、音声を停止する。
        if (isSpeaking) {
            ExpoSpeech.stop()
            setIsSpeaking(false)
            return
        }

        setIsSpeaking(true)

        // expo-speechのパラメータ設定
        const options = {
            language: 'ja',  // 日本語は'ja'を指定
            pitch: 1.0,  // 音声のピッチ
            rate: 1.0,  // 音声速度
            onDone: () => setIsSpeaking(false),  // 再生完了時の処理
            onError: () => setIsSpeaking(false) // 再生中にエラーが発生した時の処理
        }
        // テキストの内容を音声読み上げ
        ExpoSpeech.speak(text, options)
    }

    // UIの部分の補足は特にしません。
    // ヘッダー部に再生用・一時停止用アイコンを配置して、
    // アイコンを押下すると、speakingの値が変更して
    // 音声の再生・一時停止とアイコンが変更されます。
    return (
        <SafeAreaView edges={[]}>
            <Appbar.Header>
                <Appbar.BackAction onPress={() => router.back()} />
                <Appbar.Action
                    icon={isSpeaking ? "pause-circle" : "play-circle"}
                    size={32}
                    onPress={handleSpeech}
                />
            </Appbar.Header>
            <Text>{text}</Text>
        </SafeAreaView>
    )
}

こちらでAndroidエミュレータ、
iOSシミュレーターを起動して再生ボタンを押下すると、
音声が読み上げられます。

expo-speechを使って、
こんな簡単にText-To-Speechが実現できるのかと
驚きました。
今後はSpeech-To-Textの実装したいので、
実現できたら記事を作成して展開したいなと思います。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?