Skip to content

Instantly share code, notes, and snippets.

@evmcheb
Created October 27, 2019 13:16
Show Gist options
  • Save evmcheb/223bd9599154aebe1d931b9abeff0df0 to your computer and use it in GitHub Desktop.
Save evmcheb/223bd9599154aebe1d931b9abeff0df0 to your computer and use it in GitHub Desktop.
# Reads out a script using google text to speech api
from google.cloud import texttospeech
import sys
def work(tid):
with open(f"{tid}/script.txt", encoding='utf-8') as f:
lines = f.read().strip().split("\n\n")
with open("resources/rules.txt") as f:
# each line is "badword, replacement"
bad_words = [(x.split()[0], x.split()[1]) for x in f.readlines()]
title = lines[0]
for word in bad_words:
# remove bad words from title
title = title.replace(word[0], word[1])
# create a google speech api client
client = texttospeech.TextToSpeechClient()
synthesis_input = texttospeech.types.SynthesisInput(text=title)
voice = texttospeech.types.VoiceSelectionParams(
language_code='en-US',
name="en-US-Wavenet-D",
ssml_gender=texttospeech.enums.SsmlVoiceGender.MALE)
audio_config = texttospeech.types.AudioConfig(
speaking_rate=0.9,
audio_encoding=texttospeech.enums.AudioEncoding.MP3)
response = client.synthesize_speech(synthesis_input, voice, audio_config)
with open(f'{tid}/title.mp3', 'wb') as out:
out.write(response.audio_content)
for directory, body in enumerate(lines[1:]):
s = body.split("\n")
for index, line in enumerate(s):
for word in bad_words:
# remove bad words from post
line = line.replace(word[0], word[1])
line = line.replace("<br>", "\n").replace("--", "").replace("*", "")
synthesis_input = texttospeech.types.SynthesisInput(text=line)
response = client.synthesize_speech(synthesis_input, voice, audio_config)
# save the recording to it's respective folder
with open(f"{tid}/{directory:03}/{index:03}.mp3", "wb") as out:
out.write(response.audio_content)
print(f"Wrote .mp3 to {tid}/{directory:03}/{index:03}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment