Skip to content

Instantly share code, notes, and snippets.

@Mhs-220
Last active April 3, 2019 20:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mhs-220/1b6cb50772ee7f54235125515d98fb77 to your computer and use it in GitHub Desktop.
Save Mhs-220/1b6cb50772ee7f54235125515d98fb77 to your computer and use it in GitHub Desktop.
Google TTS script for GoldenDict
import os
import sys
import json
import base64
user_input = ' '.join(sys.argv[1:])
# Payload that we should send to google api
payload = '{"input":{"text":"%s"},"voice":{"languageCode":"en-US","name":"en-US-Wavenet-D"},"audioConfig":{"audioEncoding":"LINEAR16","pitch":"0.00","speakingRate":"1.00"}}' % user_input
# I used `proxychains` because this command returns 403 in my country, You can remove it if your county is not banned :)
command = f'proxychains curl \'https://cxl-services.appspot.com/proxy?url=https%3A%2F%2Ftexttospeech.googleapis.com%2Fv1beta1%2Ftext%3Asynthesize\' -H \'User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:66.0) Gecko/20100101 Firefox/66.0\' -H \'Accept: */*\' -H \'Accept-Language: en-US,en;q=0.5\' --compressed -H \'Referer: https://cloud.google.com/text-to-speech/\' -H \'Content-Type: text/plain;charset=UTF-8\' -H \'Origin: https://cloud.google.com\' -H \'Connection: keep-alive\' -H \'TE: Trailers\' --data \'{payload}\''
# Run in command line and read result
response = os.popen(command).read()
# Convert json string to Dictionary and get value
base64_audio = json.loads(response).get('audioContent')
# Write voice to file
with open('file.wav', 'wb') as file:
file.write(base64.b64decode(base64_audio))
# Play voice
os.system('play file.wav')
@Mhs-220
Copy link
Author

Mhs-220 commented Apr 3, 2019

Notes:

The code is just a mess :) I know, right?
I wrote it at 3 AM and it was just a challenge,
It can be used on Goldendict as a tts service (Or at least I used it for that)

Requirements:

  • Python 3.6.7 or higher (just for f-string in the 8th line, you can change it with % and use it in lower version (i guess))
  • sox (for play in the 17th line in the sake of use in goldendict, you can change play with something like ffplay)

How to use in goldendict:

  1. from Edit menu go to Dictionaries
  2. from Sources tab, go to Programs tab
  3. click on Add... and set enable box checked and write a Name (make sure the type is audio)
  4. write this in command: bash -c "$(python google-tts.py %GDWORD%)"

Done :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment