Advertisement
Guest User

Untitled

a guest
Dec 5th, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.29 KB | None | 0 0
  1. #!/usr/bin/python3
  2. from google.cloud import texttospeech
  3. from os.path import join as pjoin
  4. import os
  5. import sys
  6. import json
  7. import time
  8.  
  9.  
  10. VOICE_BY_GENDER = {
  11.     'male': 'ru-RU-Wavenet-B',
  12.     'female': 'ru-RU-Wavenet-C'
  13. }
  14.  
  15. # время в секундах, поставь нормальное значение
  16. TIMEOUT = 0.5
  17.  
  18.  
  19. def synthesize_text(text, outfile, voice_name='ru-RU-Standard-A'):
  20.     client = texttospeech.TextToSpeechClient()
  21.  
  22.     input_text = texttospeech.types.SynthesisInput(text=text)
  23.  
  24.     # Note: the voice can also be specified by name.
  25.     # Names of voices can be retrieved with client.list_voices().
  26.     voice = texttospeech.types.VoiceSelectionParams(
  27.         language_code='ru-RU',
  28.         name=voice_name
  29.     )
  30.  
  31.     audio_config = texttospeech.types.AudioConfig(
  32.         audio_encoding=texttospeech.enums.AudioEncoding.MP3)
  33.  
  34.     response = client.synthesize_speech(input_text, voice, audio_config)
  35.  
  36.     # The response's audio_content is binary.
  37.     out = open(outfile, 'wb')
  38.     out.write(response.audio_content)
  39.     out.close()
  40.  
  41.  
  42. def free_filename(dir, filename):
  43.     fpath = pjoin(dir, filename)
  44.     fbase, ext = os.path.splitext(fpath)
  45.     i = 0
  46.     while os.path.exists(fpath):
  47.         fpath = '%s-%d%s' % (fbase, i, ext)
  48.         i += 1
  49.     return fpath
  50.  
  51.  
  52. def save_phrases(phrases_json, dict_json, outdir):
  53.     if not os.path.exists(outdir):
  54.         os.mkdir(outdir)
  55.  
  56.     phrases_file = open(phrases_json, 'r')
  57.     dict_file = open(pjoin(outdir, dict_json), 'w')
  58.     phrases = json.load(phrases_file)
  59.     meta = []
  60.  
  61.     for phrase in phrases:
  62.         phrase_meta = {'phrase': phrase.replace("\n", "")}
  63.         for gender in ['male', 'female']:
  64.             track_fn = '%s_%s.mp3' % (phrases[phrase], gender)
  65.             phrase_meta['track_' + gender] = track_fn
  66.             synthesize_text(phrase, free_filename(outdir, track_fn), VOICE_BY_GENDER[gender])
  67.             # к примеру, здесь:
  68.             time.spleep(TIMEOUT)
  69.         meta.append(phrase_meta)
  70.    
  71.     meta_raw = json.dumps(meta, indent=4, ensure_ascii=False)
  72.     dict_file.write(meta_raw)
  73.  
  74.     phrases_file.close()
  75.     dict_file.close()
  76.  
  77.  
  78. phrases_fn = sys.argv[1]
  79. meta_fn = phrases_fn.split('.')[0] + '_meta.json'
  80. save_phrases(sys.argv[1], meta_fn, './tracks')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement