안녕하세요. 이번시간에는 지난시간까지 만들었던 아바타에 음성기능을 추가하기 위해서 텍스트를 음성으로 변환하는 라이브러리들을 배워볼거에요.
Text to Speech
pyttsx3
아바타에 텍스트 음성 변환(TTS) 기능을 추가하려면 pyttsx3, gTTS, 또는 pydub과 같은 Python 라이브러리를 사용할 수 있는데요. 본 강의에서는 오프라인에서도 잘 작동하고 다양한 TTS 엔진을 지원하는 pyttsx3를 사용하여 음성기능을 추가하는 방법을 진행하도록 하겠습니다.
필요한 라이브러리를 추가로 설치해주세요.
pip install pyttsx3
tts_by_pyttsx3.py라는 파일을 하나 생성하세요. 그리고 pyttsx3라이브러리를 포함합니다.
import pyttsx3
그리고 TTS엔진을 초기화 시킵니다.
# Initialize the text-to-speech engine
engine = pyttsx3.init()
다음으로는 텍스트를 음성으로 변환해주는 함수, text_to_speech()를 선언해주세요. 인자로는 변환할 텍스트와 음성파일 저장위치 입니다. 엔진의 setProperty()함수를 통해서 속도나 볼륨등을 조절한 뒤, 엔진의 say()함수를 호출해서 프로그램이 실행되면 텍스트를 음성으로 변환하여 재생하도록 합니다. 엔진에 텍스트와 음성파일의 저장위치도 전달하여 파일을 저장합니다. 함수의 맨 끝에 runAndWait()함수를 호출하여 음성재생이 끝날때까지 프로그램의 종료를 지연시킵니다.
# Function to convert text to speech
def text_to_speech(text, save_path=None):
engine.say(text)
# Optionally save the speech to a file
if save_path:
engine.save_to_file(text, save_path)
engine.runAndWait()
임의의 문자열을 변수에 저장하고, text_to_speech()함수에 인자로 전달하여 호출합니다. 이때, 저장할 파일명도 함께 전달합니다. 참고로 속도나 볼륨, 다른 목소리 사용하기등 pyttsx3에 대한 추가옵션을 여기에서 확인하세요.
# Example text for the avatar to speak
text = "Hello! I am your AI avatar. Nice to meet you!"
# Convert the text to speech and save it to a file
text_to_speech(text, save_path='avatar_voiceover.mp3')
완성된 코드는 아래와 같습니다.
import pyttsx3
# Initialize the text-to-speech engine
engine = pyttsx3.init()
# Function to convert text to speech
def text_to_speech(text, save_path=None):
engine.say(text)
# Optionally save the speech to a file
if save_path:
engine.save_to_file(text, save_path)
engine.runAndWait()
# Example text for the avatar to speak
text = "Hello! I am your AI avatar. Nice to meet you!"
# Convert the text to speech and save it to a file
text_to_speech(text, save_path='avatar_voiceover.mp3')
실행해볼게요.
python text_to_speech.py
해당 텍스트를 프로그램 실행하니까 바로 음성으로 제공되고, 해당 음성이 같은 폴더에 avatar_voiceover.mp3로 저장도 됩니다. Mac에서 mp3결과물을 실행해보려면 mpg123같은 음성재생라이브러리가 필요합니다.
brew install mpg123
어떤 이유에서 인지 pyttsx3로 생성한 mp3파일은 mpg123으로 재생이 안되고 에러가 나는데 이건 pyttsx3패키지 문제인것 같습니다.
$ mpg123 output_pyttsx3.mp3
High Performance MPEG 1.0/2.0/2.5 Audio Player for Layers 1, 2 and 3
version 1.32.10; written and copyright by Michael Hipp and others
free software (LGPL) without any warranty but with best wishes
Terminal control enabled, press 'h' for listing of keys and functions.
Playing MPEG stream 1 of 1: output_pyttsx3.mp3 ...
MPEG 1.0 L II cbr379 44100 stereo
[src/libmpg123/getbits.h:getbits():46] error: Tried to read 16 bits with -13 available.
[src/libmpg123/layer2.c:INT123_do_layer2():365] error: missing bits in layer II step two
[src/libmpg123/getbits.h:getbits():46] error: Tried to read 16 bits with -13 available.
[src/libmpg123/getbits.h:getbits():46] error: Tried to read 16 bits with -29 available.
[src/libmpg123/getbits.h:getbits():46] error: Tried to read 16 bits with -45 available.
[src/libmpg123/layer2.c:INT123_do_layer2():365] error: missing bits in layer II step two
Note: Illegal Audio-MPEG-Header 0x00f00210 at offset 6636.
Note: Trying to resync...
Note: Skipped 466 bytes in input.
Warning: Big change from first (MPEG version, layer, rate). Frankenstein stream?
> 02+65 00:00.20+00:06.79 --- 100=100 0 kb/s 1237 B acc 1656 clip p+0.000
MPEG 2.5 L II cbr95 11025 j-s
Note: Illegal Audio-MPEG-Header 0x2bd520d3 at offset 8339.
Note: Trying to resync...
Note: Skipped 658 bytes in input.
Warning: Big change from first (MPEG version, layer, rate). Frankenstein stream?
> 03+76 00:00.14+00:03.65 --- 100=100 80 kb/s 481 B acc 1179 clip p+0.000
MPEG 2.5 L III cbr80 12000 mono
Note: Illegal Audio-MPEG-Header 0xe027de53 at offset 9478.
Note: Trying to resync...
Note: Skipped 1024 bytes in input.
[src/libmpg123/parse.c:wetwork():1389] error: Giving up resync after 1024 bytes - your stream is not nice... (maybe increasing resync limit could help).
main: [src/mpg123.c:play_frame():866] error: ...in decoding next frame: Failed to find valid MPEG data within limit on resync. (code 28)
This was a Frankenstein track.
[0:00] Decoding of output_pyttsx3.mp3 finished.
gtts
이번에는 gtts를 이용해서 TTS를 구현해 보도록 하겠습니다.
gtts를 설치해주세요.
pip install gtts
그리고 tts_by_gtts.py를 생성해서 아래 코드를 저장해주세요.
from gtts import gTTS
tts = gTTS("Hello, world!", lang="en")
tts.save("output_gtts.mp3")
실행해 보시면 output_gtts.mp3가 생성되어 있을거에요.
python tts_by_gtts.py
gtts로 만든 파일은 mpg123를 이용해서 재생할 수 있습니다.
mpg123 output_gtts.mp3
그런데 얘는 다양한 목소리 지원이나 속도, 볼륨조절등의 옵션은 없어요. 그럼 다음시간에 마지막으로 애니메이션과 음성을 병합하는 코드 함께 해볼게요.