ツタンラーメンの忘備録

プログラミングや精神疾患、ラーメンについて書いていきます。たぶん。

python 読み上げ テキストファイル 一行ずつ 速度 変える キーイベント

タイトルが長いですが今回の要件を整理します

  • pythonを使う
  • 文字を読み上げる
  • 内容はテキストファイルである
  • キーイベントで一行ずつ読み上げる

って感じです.ちなみに今回はWindows10を使っています.Macではできません.

ではコード

import win32com.client as wincl
import glob
import os
import random

speak = wincl.Dispatch("SAPI.SpVoice")
speak.Rate = -3


def read_files():
    path = "テキストファイルまでのパス"
    f = open(path) 
    lines = f.readlines()
    f.close()

    return lines

def speak_lines():
    lines = read_files()
  speak_line = -1

    while True:
        input_word = input("""
コマンドを選んでください
r->同じ行を繰り返して読む
u->次の行を読み上げる
d->前の行を読み上げる
>""")
        if input_word == "u":
            if speak_line < len(lines) - 1:
                speak_line += 1
                speak.Speak(lines[speak_line])
        elif input_word == "d":
            if speak_line > 1:
                speak_line -= 1
                speak.Speak(lines[speak_line]))
        elif input_word == "r":
            if 0 <= speak_line and speak_line < len(lines) - 1:
                speak.Speak(lines[speak_line])
        elif input_word in ["1", "2", "3", "4", "5", "6", "7", "8", "9"]:
            speak.Rate = int(input_word) - 6

if __name__ == '__main__':
    speak_scripts()

別のこといろいろしていたのでちょっと効率の悪いことしているのは許してください.
数字を入力すると読み上げスピードが変わります.全体的に見たままです.

speak.Speak("読み上げたい文章")
speak.Rate = Long型 -> スピード(ピッチ?)の変更