행위

Python 구글 TTS 오디오 재생

DB CAFE

thumb_up 추천메뉴 바로가기


1 라이브러리 설치[편집]

pip install gTTS
pip install pydub

pip install simpleaudio

2 TTS 예제[편집]

import os
from glob import glob
from io import BytesIO

from gtts import gTTS
from pydub import AudioSegment
from pydub.playback import play


def tts(word, toSlow=True):
    tts = gTTS(text=word, lang="ko", slow=toSlow)
    fp = BytesIO()
    tts.write_to_fp(fp)
    fp.seek(0)

    # simpleaudio가 있어야 작동한다.
    song = AudioSegment.from_file(fp, format="mp3")
    play(song)

    # ffcache 파일이 생성돼서 glob wild card로 전부 삭제
    fileList = glob("./ffcache*")
    for filePath in fileList:
        os.remove(filePath)
        
        
 if __name__ == "__main__":
     tts("안녕", toSlow=False)  # 안녕 빠르게 발음
     tts("안녕", toSlow=True)  # 안녕 느리게 발음