> For the complete documentation index, see [llms.txt](https://ritka.gitbook.io/translate-book/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ritka.gitbook.io/translate-book/9.5.1.-ispolzovanie-preobrazovaniya-teksta-v-rech-v-uzle-ros.md).

# 9.5.1. Использование преобразования текста в речь в узле ROS

До сих пор мы использовали только голоса Фестиваля из командной строки. Чтобы увидеть, как использовать преобразование текста в речь из узла ROS, давайте взглянем на скрипт talkback.py, который можно найти в каталоге rbx1\_speech / node.&#x20;

Ссылка на источник: [talkback.py](https://github.com/pirobot/rbx1/blob/indigo-devel/rbx1_speech/nodes/talkback.py)

```
#!/usr/bin/env python 
import rospy
from std_msgs.msg import String
from sound_play.libsoundplay import SoundClient
import sys
class TalkBack:
def __init__(self, script_path):
rospy.init_node('talkback')
rospy.on_shutdown(self.cleanup) 13.
# Set the default TTS voice to use
self.voice = rospy.get_param("~voice", "voice_don_diphone")
# Set the wave file path if used
self.wavepath = rospy.get_param("~wavepath", script_path +
"/../sounds")
# Create the sound client object
self.soundhandle = SoundClient()
# Wait a moment to let the client connect to the
# sound_play server
rospy.sleep(1)
# Make sure any lingering sound_play processes are stopped.
self.soundhandle.stopAll()
# Announce that we are ready for input
self.soundhandle.playWave(self.wavepath + "/R2D2a.wav")
rospy.sleep(1)
self.soundhandle.say("Ready", self.voice)
rospy.loginfo("Say one of the navigation commands...") 36.
# Subscribe to the recognizer output and set the callback
function
rospy.Subscriber('/recognizer/output', String, self.talkback)
def talkback(self, msg):
# Print the recognized words on the screen
rospy.loginfo(msg.data)
# Speak the recognized words in the selected voice
self.soundhandle.say(msg.data, self.voice)
# Uncomment to play one of the built-in sounds #rospy.sleep(2)
#self.soundhandle.play(5)
# Uncomment to play a wave file
#rospy.sleep(2) #self.soundhandle.playWave(self.wavepath + "/R2D2a.wav")
def cleanup(self):
self.soundhandle.stopAll() rospy.loginfo("Shutting down talkback node...")
if __name__=="__main__": try:
TalkBack(sys.path[0])
rospy.spin()
except rospy.ROSInterruptException:
rospy.loginfo("AMCL navigation test finished.")
```

Давайте посмотрим на ключевые строки сценария.

```
from sound_play.libsoundplay import SoundClient
```

Скрипт общается с сервером sound\_play с помощью класса SoundClient, который мы импортируем из библиотеки sound\_play.

```
self.voice = rospy.get_param("~voice", "voice_don_diphone")
```

Установите голос фестиваля для преобразования текста в речь. Это может быть переопределено в файле запуска.

```
self.wavepath = rospy.get_param("~wavepath", script_path + "/../sounds")
```

Установите путь для чтения волновых файлов. Клиенту и серверу sound*play нужен полный путь к волновым файлам, поэтому мы читаем в scriptpath из переменной окружения sys.path \[0] (см. Блок «\_\_main*» в конце скрипта.)

```
self.soundhandle = SoundClient()
```

Создайте дескриптор объекта SoundClient ().

```
self.soundhandle.playWave(self.wavepath + "/R2D2a.wav")
rospy.sleep(1)
self.soundhandle.say("Ready", self.voice)
```

Используйте объект self.soundhandle для воспроизведения коротковолнового файла (звук R2D2) и произнесите «Готов» голосом по умолчанию.

```
def talkback(self, msg):
# Print the recognized words on the screen
rospy.loginfo(msg.data) 43.
# Speak the recognized words in the selected voice
self.soundhandle.say(msg.data, self.voice)
```

Это наш обратный вызов при получении сообщений в теме /ognizer / output. Переменная msg содержит текст, произнесенный пользователем, который распознается узлом PocketSphinx. Как видите, мы просто выводим распознанный текст обратно на терминал, а также произносим его, используя голос по умолчанию.

Чтобы узнать больше об объекте SoundClient, взгляните на API [libsoundplay](http://www.ros.org/doc/api/sound_play/html/libsoundplay_8py_source.html) в ROS Wiki.
