Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

python - Text to Speech when button pressed on Raspberry pi

I am trying to get a a raspberry pi to convert text to speech every time I press a button

I have a file (conversation.txt) which contains three sentences (on separate lines). I would like a script which splits the text file into three sentences, and then whenever the pi button is pressed converts each sentence into speech

So far I have managed to cobble together code for the three separate tasks, but I do not know how to join them together.

Code 1. splits the file and save the output in a list with three elements.

def splitConversation():
    route = []
    with open('conversation.txt', 'r') as f:
        for line in f:
            route.extend(line.strip().split('>'))
#    print(route)
    return route

splitConversation()

Code 2. Converts text to speech using the GTTS library (google text to speech) saving the output as an mp3

from gtts import gTTS

#Reading the text file and store into object called text
file = open("conversation.txt", "r").read().replace("
", " ")

language = 'en'

#Passing the text file into gTTS module and store into speech
speech = gTTS(text = str(file), lang = language, slow = False)

#Saving the converted audio in a mp3
speech.save("voice.mp3")  # save each sentence as a seperate mp3

Code 3. Plays an mp3 when a button is pressed on the pi

from gpiozero import Button
import pygame

pygame.init()
btn = Button(17)

beat1 = pygame.mixer.sound('/home/pi/conversation/file.mp3') # should use the generated mp3 files

def conversation():
    beat1.play()

btn.when_pressed = conversation

Essentially, I would like the GTTS library to convert the split file into mp3 files, and then have the pi play each mp3 every time the button is pressed.

Any help greatly appreciated as I have just started to code so am a noob. Hope the above makes sense


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...