Advertisement
Guest User

bcigui

a guest
Jun 27th, 2017
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.79 KB | None | 0 0
  1. // bcigui_cspeechclient
  2. @echo off
  3. echo "bcigui cspeechclient called"
  4. "C:\Python27\python.exe" "CereVoiceClient\examples\python\speakTTS.py" -n %1
  5.  
  6. // speakTTS.bat CerevoiceClient\examples\python
  7. c:\Python27\python.exe C:\Experiments\Z020\CereVoiceClient\examples\python\speakTTS.py %1 %2
  8.  
  9. // speakTTS.py
  10. #coding: utf-8
  11. #-------------------------------------------------------------------------------
  12. # Name: speakTTS
  13. # Purpose: Without argument(s) --new or --last it creates a socket connection to the appropreate BCIApplication and waits for text from there and speaks it.
  14. # With arg -n (--new) or -l (--last) it uses the Cereproc cServer to create the new sound and then plays it.
  15. # call speakTTS -h to show all options
  16. # Cereproc cServer must be installed and running
  17. #
  18. # Author: battes
  19. #
  20. # Created: 22.07.2015
  21. # last edit: 08.04.16
  22. # - removed overhead for usage with BCI GUI, further cleaning up is needed
  23. # Copyright: (c) battes 2015
  24. # Licence: <your licence>
  25. #-------------------------------------------------------------------------------
  26. import sys
  27. import os
  28. import string
  29. import pygame
  30. import time
  31. import socket
  32. import select
  33.  
  34. maxBackup = 200 # Maximum number of entries for backup list of spoken text
  35.  
  36. def setupenv():
  37. thirdpartydir = os.path.join(os.path.split(os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])[0], "3rdparty", "lib")
  38. cspeechdir = os.path.join(os.path.split(os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])[0], "cSpeech", "lib")
  39. os.environ['PATH'] = os.environ['PATH'] + os.pathsep + thirdpartydir + os.pathsep + cspeechdir
  40. sys.path.append(os.path.join(os.path.split(os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])[0], "cSpeech", "pylib"))
  41.  
  42. def readSocket(serversocket, timeout):
  43. ret = 'None'
  44. try:
  45. readable, writable, errored = select.select([serversocket], [], [],timeout) # timeout prevents blocking through accept()
  46. except:
  47. return ret
  48. for s in readable:
  49. if s is serversocket:
  50. clientsocket, address = serversocket.accept() # blocked: waiting for input
  51. print "Connection from", address
  52. ret = clientsocket.recv(1024)
  53. print 'ret', ret
  54. if ret:
  55. pass
  56. else:
  57. s.close()
  58.  
  59. return ret
  60.  
  61.  
  62. def writeFile(infile, text):
  63. global args
  64.  
  65. f1 = open(infile,'w')
  66. f1.write(text)
  67. f1.close()
  68.  
  69. # backup text list
  70. # write new line on top of file
  71. inpath, file = os.path.split(infile)
  72. try:
  73. with open(inpath +'/TTS_Backup.Txt', 'r+') as f1:
  74. content = f1.read()
  75. if text in content:
  76. content = content.replace(text.rstrip('\r\n') + '\n', '')
  77. cont = content.split('\n')
  78. if len(cont) > maxBackup:
  79. f1.close()
  80. with open(inpath +'/TTS_Backup.Txt', 'w') as f2:
  81. content = content.replace('\n'+cont[-1], '')
  82. f2.write(text.rstrip('\r\n') + '\n' + content)
  83. else:
  84. f1.seek(0, 0)
  85. f1.write(text.rstrip('\r\n') + '\n' + content)
  86.  
  87. except IOError:
  88. # very first line
  89. with open(inpath +'/TTS_Backup.Txt', 'w') as f1:
  90. f1.write(text.rstrip('\r\n'))
  91.  
  92.  
  93.  
  94. def createNewSound(args, newText):
  95. global CereSpeechclient
  96. writeFile(args.infile, newText)
  97.  
  98. res = CereSpeechclient.run_client(args.host, int(args.port), args.outdir, args.voice, args.textmode, args.asynch, args.stream, args.headinfo, args.verbose, [args.infile])
  99.  
  100. def speakLatest(soundfile):
  101. f = open(soundfile, 'rb')
  102.  
  103. data = f.read()
  104.  
  105. sound = pygame.mixer.Sound(data)
  106. plays = sound.play()
  107. while plays.get_busy(): # needed when speakTTS is startet from terminal
  108. pygame.time.delay(100) # otherwise prog returns immediately after start - no sound!
  109.  
  110.  
  111. def speak(args, newText):
  112. print 'text to speak:', newText
  113. print args.infile
  114. inpath, infile = os.path.split(args.infile)
  115. soundFile, ext = os.path.splitext(infile)
  116. soundFile += '.raw'
  117.  
  118.  
  119. try:
  120. port = int(args.port)
  121. except ValueError:
  122. parser.error("Port number has to be an integer")
  123.  
  124. if newText == 'latest':
  125. speakLatest(args.outdir +soundFile)
  126. else:
  127. createNewSound(args, newText)
  128. speakLatest(args.outdir +soundFile)
  129.  
  130.  
  131.  
  132.  
  133. def main():
  134. global root, args, CereSpeechclient
  135. from optparse import OptionParser
  136. import argparse
  137.  
  138. print "using speakTTS.py"
  139.  
  140. setupenv()
  141. import CereSpeechclient
  142.  
  143. pygame.mixer.quit()
  144. pygame.mixer.init(frequency=22050, size=16, channels=1)
  145.  
  146. repRate = 1 # 0.5 # in Sec
  147.  
  148. # Setup option parsing
  149. usage="usage: %prog [options] infiles\n"
  150. parser = argparse.ArgumentParser(description='This is to call Text To Speech')
  151.  
  152.  
  153. # Options
  154. parser.add_argument("-n", "--new", nargs='*', dest="newtext", default=[" ","", " "], help="new text to speak (write into input file)")
  155. parser.add_argument("-H", "--host", dest="host", default="localhost", help="Host name (default: localhost)")
  156. parser.add_argument("-p", "--port", dest="port", default="8989", help="Port number (default: 8989)")
  157. parser.add_argument("-i", "--infile", dest="infile", default="../../../TTS.txt", help="Input file including directory")
  158. parser.add_argument("-o", "--outdir", dest="outdir", default="../../../", help="Output directory")
  159. parser.add_argument("-V", "--voice", dest="voice", default=None, help="(Case-sensitive) Voice name (Gudrun or Alex)")
  160. parser.add_argument("-t", "--textmode", dest="textmode", action = "store_true", default=True, help="Flag: input files contain text")
  161. parser.add_argument("-a", "--asynch", dest="asynch", action = "store_true", default=False, help="Flag: use asynchronous socket")
  162. parser.add_argument("-s", "--stream", dest="stream", action = "store_true", default=False, help="Flag: stream the data")
  163. parser.add_argument("-hd", "--headinfo", dest="headinfo", action = "store_true", default=False, help="Flag: print voice header information")
  164. parser.add_argument("-v", "--verbose", dest="verbose", action = "store_true", default=False, help="Flag: print callback info messages")
  165. parser.add_argument("-l", "--last", dest="last", action = "store_true", default=False, help="Flag: speak last text")
  166.  
  167. args = parser.parse_args()
  168.  
  169. print args
  170.  
  171. newText = string.join(args.newtext).strip()
  172. fs_encoding = sys.getfilesystemencoding()
  173. newText = newText.decode(fs_encoding)
  174. newText = newText.encode("utf-8")
  175.  
  176. if args.last:
  177. newText = 'latest'
  178.  
  179. if newText.strip() != '':
  180. speak(args, newText)
  181.  
  182. if __name__ == '__main__':
  183. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement